Skip to content

Instantly share code, notes, and snippets.

@Misaka-0x447f
Created February 6, 2019 07:18
Show Gist options
  • Save Misaka-0x447f/47c3046b26a605055a3308998659ed51 to your computer and use it in GitHub Desktop.
Save Misaka-0x447f/47c3046b26a605055a3308998659ed51 to your computer and use it in GitHub Desktop.
Javascript object proxy
const original = {
a: 1,
b: {
c: 1
}
}
const handler = {
get: (target, name) => {
return target[name];
},
set: (obj, prop, value) => {
const ori = obj[prop];
obj[prop] = value;
// listen to any update here.
console.log(`mutation at ${prop}`);
console.log(`>>> ${ori}`);
console.log(`<<< ${value}`);
}
}
const watched = new Proxy(original, handler);
watched.a = 2;
watched.b.c = 3; // will not be watched.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment