Javascript – Object watch (on all browsers)

Javascript’s object.watch is a function which tends to work only on Firefox.. How do we make it work on other browsers? Below is the code snippet to achieve this:-

 

Common JS Snippet for making object.watch to work on all browsers

if (!Object.prototype.watch) {
Object.defineProperty(Object.prototype, “watch”, {
enumerable: false
, configurable: true
, writable: false
, value: function (prop, handler) {
var
oldval = this[prop]
, newval = oldval
, getter = function () {
return newval;
}
, setter = function (val) {
oldval = newval;
return newval = handler.call(this, prop, oldval, val);
}
;

if (delete this[prop]) { // can’t watch constants
Object.defineProperty(this, prop, {
get: getter
, set: setter
, enumerable: true
, configurable: true
});
}
}
});
}

// object.unwatch
if (!Object.prototype.unwatch) {
Object.defineProperty(Object.prototype, “unwatch”, {
enumerable: false
, configurable: true
, writable: false
, value: function (prop) {
var val = this[prop];
delete this[prop]; // remove accessors
this[prop] = val;
}
});
}

 

Code Example:-

//Create an object and assign a initial value

var my_object = { blog_name:  “selvaonrails.wordpress.com” };

//Adding listener (watcher)

my_object.watch(‘blog_name‘, function (id, oldval, newval) {
console.log(‘my_object.’ + id + ‘ changed from ‘ + oldval + ‘ to ‘ + newval);
return newval;
});

Now changing the value of blog_name will print the console statement:-

my_object.blog_name=”SelvaOnRails”