Skip to content

Instantly share code, notes, and snippets.

@fiveisprime
Created December 1, 2012 03:02
Show Gist options
  • Select an option

  • Save fiveisprime/4180364 to your computer and use it in GitHub Desktop.

Select an option

Save fiveisprime/4180364 to your computer and use it in GitHub Desktop.
watch
var watch = function(obj, prop, callback) {
var oldValue = obj[prop]
, newValue = oldValue
, getter = function() { return newValue; }
, setter = function(value) {
oldValue = newValue;
newValue = value;
callback.call(obj, prop, oldValue, newValue);
};
// Attempt to delete the property. If this fails, the configurable
// flag is set to false which means that any changes to the property
// will throw a TypeError.
if (delete obj[prop]) {
if (Object.defineProperty) {
// ECMAScript 5 standard.
Object.defineProperty(obj, prop, {
get: getter,
set: setter
});
} else if (Object.prototype.__defineGetter__ && Object.prototype.__defineSetter__) {
// Older browsers.
Object.prototype.__defineGetter__(obj, prop, getter);
Object.prototype.__defineSetter__(obj, prop, setter);
}
}
return this;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment