Skip to content

Instantly share code, notes, and snippets.

@lucasmenendez
Last active July 14, 2018 11:15
Show Gist options
  • Save lucasmenendez/dc07b5adafddbe06c817e5c7d78b4f07 to your computer and use it in GitHub Desktop.
Save lucasmenendez/dc07b5adafddbe06c817e5c7d78b4f07 to your computer and use it in GitHub Desktop.
Deep watcher over objects
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