Skip to content

Instantly share code, notes, and snippets.

@hufyhang
Created December 26, 2015 14:25
Show Gist options
  • Save hufyhang/47b67113f048fe00b153 to your computer and use it in GitHub Desktop.
Save hufyhang/47b67113f048fe00b153 to your computer and use it in GitHub Desktop.
/*
* Object.watch shim
*
* 2015-12-26
*
* By Feifei Hang, http://feifeihang.info
* Public Domain.
* NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
*/
(function () {
// Object.watch
if (typeof Object.watch === 'undefined') {
Object.watch = function watch(obj, prop, handler) {
var oldVal = obj[prop];
var newVal = oldVal;
delete obj[prop];
Object.defineProperty(obj, prop, {
enumerable: true,
configurable: true,
get: function () { return newVal; },
set: function (val) {
oldVal = newVal;
return newVal = handler.call(obj, prop, oldVal, val) || val;
}
});
};
}
// Object.unwatch
if (typeof Object.unwatch === 'undefined') {
Object.unwatch = function unwatch (obj, prop) {
var val = obj[prop];
delete obj[prop];
obj[prop] = val;
};
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment