Created
December 1, 2012 03:02
-
-
Save fiveisprime/4180364 to your computer and use it in GitHub Desktop.
watch
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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