melanke / Watch.JS

watch the changes of any object or attribute

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

unwatchOne gets NRE if property is added after watch is called

Sempiternity87 opened this issue · comments

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]) {

Hi,

Thanks for the fix.