Created
February 6, 2019 07:18
-
-
Save Misaka-0x447f/47c3046b26a605055a3308998659ed51 to your computer and use it in GitHub Desktop.
Javascript object proxy
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
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