melanke / Watch.JS

watch the changes of any object or attribute
Other
2.14k stars 219 forks source link

unwatchOne gets NRE if property is added after watch is called #101

Closed Sempiternity87 closed 6 years ago

Sempiternity87 commented 7 years ago

If you start watching an object, then add an object as a new property to it, the unwatchOne gets an error when trying to access properties from watchers of this new object. Since it didn't exist when first watched, it never got the watchers property, and causes a Null Reference Exception.

var obj = {};
var watchFunc = function(prop, action, difference, oldValue)
  {
  if (!(prop == 'modified' || obj.modified)) obj.modfied = true;
  };
obj.prop1 = 'Hello';
watch(obj, watchFunc, 2);
obj.items = [{'prop2':'Hello'},{'prop3':'World'}];
unwatch(obj, watchFunc);
//Cannot read property 'prop2' of undefined (looking for obj.watchers[prop]
//where watchers doesn't exist).

suggest changing if (obj.watchers[prop]) { to if (obj.watchers && obj.watchers[prop]) {

xwisdom commented 7 years ago

Hi,

Thanks for the fix.