-
-
Save trevmex/669772 to your computer and use it in GitHub Desktop.
This file contains 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
/* | |
* user.watch v1.0: Cross-browser user.watch | |
* From http://code.eligrey.com/object.watch/ | |
* | |
* By Elijah Grey, http://eligrey.com | |
* Tweaked by Trevor Lalish-Menagh, http://trevmex.com | |
* | |
* A shim that partially implements object.watch and object.unwatch | |
* in browsers that have accessor support. | |
* | |
* Public Domain. | |
* NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. | |
*/ | |
var User = function () { | |
return { | |
// user.watch | |
"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 | |
User.prototype.__defineGetter__.call(this, prop, getter); | |
User.prototype.__defineSetter__.call(this, prop, setter); | |
} | |
} | |
}, | |
// user.unwatch | |
"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