Skip to content

Instantly share code, notes, and snippets.

@amitv87
Created October 15, 2018 05:53
Show Gist options
  • Save amitv87/5162b358bc0eb8343a1c461adcd072a0 to your computer and use it in GitHub Desktop.
Save amitv87/5162b358bc0eb8343a1c461adcd072a0 to your computer and use it in GitHub Desktop.
Object.defineProperty(Object.prototype, "watch", {
writable: false,
enumerable: false,
configurable: true,
value: function(prop, handler){
var propVal = this[prop];
Object.defineProperty(this, prop, {
get: () => propVal,
set: (val) => {
handler(this, val, propVal);
propVal = val;
return propVal;
},
enumerable: true,
configurable: true,
});
}
});
Object.defineProperty(Object.prototype, "unwatch", {
writable: false,
enumerable: false,
configurable: true,
value: function(prop){
var val = this[prop];
delete this[prop]; // remove accessors
this[prop] = val;
}
});
var test = {};
test.watch("hello", (obj, newval, oldval)=>{
console.log('modified hello from', oldval, 'to', newval);
});
test.hello = "world"; // triggers the watch handler
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment