-
-
Save dreamerchandra/709cfcdeda52620366a98740c7ee584c to your computer and use it in GitHub Desktop.
object.watch polyfill in ES5
This file contains hidden or 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
//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