Created
October 15, 2018 05:53
-
-
Save amitv87/5162b358bc0eb8343a1c461adcd072a0 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
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