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

$watch should consider two NaNs to be equal

Open IgorMinar opened this issue 15 years ago • 4 comments

recently in feedback we got into a situation where an infinite digest was caused by a watch that returned an object with NaN values. we should be smart enough to consider two NaNs to be equal.

Test case: http://jsfiddle.net/IgorMinar/CHVbb/184/

IgorMinar avatar Nov 15 '11 19:11 IgorMinar

the fix should be done in the equals method that $digest uses when executing watchers:

if ((value = watch.get(current)) !== (last = watch.last) && !equals(value, last)) {

the equals should take another boolean argument which if true should result in equals considering two NaNs to be equal.

IgorMinar avatar Nov 15 '11 19:11 IgorMinar

Sure I can work on this :)

Codier avatar Nov 15 '11 21:11 Codier

There is a complication in $watch function,

              watcher = {
              fn: listenFn,
              last: Number.NaN, // NaN !== NaN. We used this to force $watch to fire on first run.
              get: get,
              exp: watchExp
            };

If we apply the fix you suggested, and on first digest cycle the expression evaluates to NaN, then the function attached to watcher will not run at all even for the first time.

A workaround probably will be to have a firstRun boolean property attached to each watcher and delete it after firstrun

              watcher = {
              fn: listenFn,
              last: Number.NaN, // NaN !== NaN. We used this to force $watch to fire on first run.
              get: get,
              exp: watchExp,
              firstRun: true
            };
//inside the digest function
   if ((value = watch.get(current)) !== (last = watch.last) && !equals(value, last, !watcher.firstRun)} {
       delete watcher.firstRun
  }
//....
   

Codier avatar Nov 16 '11 01:11 Codier

landed as 29f9e2665d8b771a6226870fc8fd2c4c94d7a2c0

thanks!

IgorMinar avatar Nov 21 '11 23:11 IgorMinar