Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Proxy / Reflect based object watcher
const obj = {
name: 'Erdem',
surname: 'Arslan'
}
const onChange = (watch, callback) => {
const handler = {
get (target, prop, receiver) {
callback(target, prop, receiver)
const value = Reflect.get(target, prop, receiver)
if (typeof value === 'object') {
return new Proxy(value, handler)
}
return value
},
set (target, prop, value) {
callback(target, prop, value)
return Reflect.set(target, prop, value)
},
del (target, prop) {
callback(target, prop)
return Reflect.deleteProperty(target, prop)
}
}
return new Proxy(watch, handler)
}
const logger = event => console.log(event)
const proxy = onChange(obj, logger)
proxy.name = 'Dias'
console.log(proxy)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment