angular.js icon indicating copy to clipboard operation
angular.js copied to clipboard

Bug in $watchCollection + angular.bind ?

Open xbagir opened this issue 12 years ago • 3 comments

Controller:

this.data = {num: 1};

$scope.$watchCollection(angular.bind(this, function () {
   return this.data;
}), angular.bind(this, function (newData, oldData) {
   console.log(newData)
   console.log(oldData);
}));

$timeout(angular.bind(this,function(){
    this.data.num = 2;         
}), 3000);

Why after a timeout console.log (oldData) === undefined? This behavior seems to be a bug.

xbagir avatar Jun 17 '14 06:06 xbagir

This is because $watchCollection only tracks the old value if the listener accepts more than 1 argument, and the function returned by angular.bind has a signature with no arguments. ($watchCollection code)

I'm not sure what's a good solution for this, and if always tracking the old value is a good idea (probably not)

rodyhaddad avatar Jun 25 '14 17:06 rodyhaddad

I don't think there is any elegant way to deal with this specific problem. Arrow functions or native .bind() are simply much better choice in this case. Since this is very old and very rare issue, I think it can be safely closed now, but it's your decision of course :)

4O4 avatar Oct 15 '17 20:10 4O4

I think that the only workaround is to use a bit of that here. I don't think that transpilers (CoffeeScript, TypeScript etc) use bind do they?

petebacondarwin avatar Oct 15 '17 20:10 petebacondarwin