Skip to content

Instantly share code, notes, and snippets.

@rendfall
Created November 5, 2015 09:06
Show Gist options
  • Select an option

  • Save rendfall/747e2c339f5de638d3fa to your computer and use it in GitHub Desktop.

Select an option

Save rendfall/747e2c339f5de638d3fa to your computer and use it in GitHub Desktop.
Object.watch by Eli Grey’s
// object.watch by Eli Grey: https://gist.github.com/eligrey/175649
if (!Object.prototype.watch)
{
Object.prototype.watch = function (prop, handler)
{
var val = this[prop],
getter = function ()
{
return val;
},
setter = function (newval) {
return val = handler.call(this, prop, val, newval);
};
if (delete this[prop]) { // can't watch constants
if (Object.defineProperty) { // ECMAScript 5
Object.defineProperty(this, prop, {
get: getter,
set: setter
});
}
else if (Object.prototype.__defineGetter__ &&
Object.prototype.__defineSetter__) //legacy
{
Object.prototype.__defineGetter__.call(this, prop, getter);
Object.prototype.__defineSetter__.call(this, prop, setter);
}
}
};
}
// object.unwatch
if (!Object.prototype.unwatch)
{
Object.prototype.unwatch = function (prop) {
var val = this[prop];
delete this[prop]; // remove accessors
this[prop] = val;
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment