Skip to content

Instantly share code, notes, and snippets.

@johnnymillergh
Last active August 20, 2020 06:08
Show Gist options
  • Save johnnymillergh/f509f3536f17decc7a5186ef1609fa53 to your computer and use it in GitHub Desktop.
Save johnnymillergh/f509f3536f17decc7a5186ef1609fa53 to your computer and use it in GitHub Desktop.
Proxy and reflect in JavaScript
/**
* Observe an object by proxy
* @param {*} object
* @param {function} callback function
* @returns {Proxy} the proxy of object
*/
function observe (object, callback) {
return new Proxy(object, {
get (target, key, receiver) {
return Reflect.get(target, key, receiver)
},
set (target, key, value) {
if (typeof value === 'object') {
const recursive = observe(value, callback)
Reflect.set(target, key, recursive)
callback(key, recursive)
return
}
Reflect.set(target, key, value)
callback(key, value)
},
deleteProperty (target, propertyKey) {
callback(propertyKey, Reflect.get(target, propertyKey))
Reflect.deleteProperty(object, propertyKey)
}
})
}
const objectProxy = observe(
{ id: 1, name: 'Johnny' },
(key, value) => {
if (typeof value === 'object') {
console.info(`Observed field change! [${key}]: ${JSON.stringify(value)}`)
return
}
console.info(`Observed field change! [${key}]: ${value}`)
}
)
objectProxy.id = 2
objectProxy.name = 'Johnny Miller'
objectProxy.otherObject = {
id: 2,
name: 'Mario'
}
console.info('otherObject', objectProxy.otherObject)
delete objectProxy.otherObject
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment