Last active
July 14, 2018 11:15
-
-
Save lucasmenendez/dc07b5adafddbe06c817e5c7d78b4f07 to your computer and use it in GitHub Desktop.
Deep watcher over objects
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
if (!Object.prototype.deepWatch) { | |
Object.prototype.deepWatch = function(f) { | |
let res = {}; | |
Object.keys(this).forEach(k => { | |
let src = this[k]; | |
if (Array.isArray(src)) { | |
res[k] = new Proxy(src, { | |
set(src, i, val) { | |
if (i !== "length") f.call(this, src, [...src, val]); | |
return Reflect.set(...arguments); | |
}, | |
get() { return Reflect.get(...arguments); } | |
}); | |
} else if (typeof src === "object") { | |
res[k] = this[k].deepWatch(f); | |
} else if (typeof src !== "function") { | |
let _k = `_${ k }`; | |
res[_k] = src; | |
Object.defineProperty(res, k, { | |
set(val) { | |
f.call(this, this[_k], val); | |
this[_k] = val; | |
}, | |
get() { return this[_k]; } | |
}); | |
} else { | |
res[k] = src; | |
} | |
}); | |
return res; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment