Skip to content

Instantly share code, notes, and snippets.

@hamburgerwang
Forked from eligrey/object-watch.js
Created January 4, 2012 00:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hamburgerwang/1557786 to your computer and use it in GitHub Desktop.
Save hamburgerwang/1557786 to your computer and use it in GitHub Desktop.
object.watch polyfill
// Cross-browser object.watch and object.unwatch
// object.watch
if (!Object.prototype.watch) {
Object.prototype.watch = 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
if (Object.defineProperty) { // ECMAScript 5
Object.defineProperty(this, prop, {
get: getter,
set: setter,
enumerable: false,
configurable: true
});
} 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