Skip to content

Instantly share code, notes, and snippets.

@dreamerchandra
Forked from eligrey/object-watch.js
Last active January 23, 2019 22:15
Show Gist options
  • Save dreamerchandra/709cfcdeda52620366a98740c7ee584c to your computer and use it in GitHub Desktop.
Save dreamerchandra/709cfcdeda52620366a98740c7ee584c to your computer and use it in GitHub Desktop.
object.watch polyfill in ES5
//Original code : https://gist.github.com/eligrey/384583
// modification
//Objects like JSON can be observed using this
if (!Object.prototype.watch) {
Object.defineProperty(
Object.prototype,
"watch", {
enumerable: false,
configurable: true,
writable: false,
value: function (prop, handler) {
var old = this[prop];
if(old){
if(Object.keys(old).length>0){
var keys = Object.keys(old);
keys.forEach((ele)=>{
// console.log('inside',ele,this,this.ele);
this[prop].watch(`${ele}`,handler);
})
}
}
var cur = old;
var getter = function () {
return cur;
};
var setter = function (val) {
old = cur;
cur = handler.call(this,prop,old,val);
return cur;
};
// can't watch constants
if (delete this[prop]) {
Object.defineProperty(this,prop,{
get: getter,
set: setter,
enumerable: true,
configurable: true
});
}
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment