Last active
March 16, 2022 14:20
-
-
Save monkeymonk/8699c3c8bb2fb912c94b96bc08778b97 to your computer and use it in GitHub Desktop.
JavaScript Watch helper
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
/** | |
* @example | |
* const item = watch({}, (value, prop, source) => { | |
* if (prop === 'foo' && !value) { | |
* return 'default_value'; | |
* } | |
* | |
* if (prop === 'baz') { | |
* return 'nope'; | |
* } | |
* | |
* return value; | |
* }); | |
* | |
* delete item.foo; | |
* console.log(item.foo); // return 'default_value' | |
* | |
* item.baz = 'ok'; | |
* console.log(item.baz); // return 'nope' | |
* | |
* @param value | |
* @param handler | |
*/ | |
export function watch(value, handler = (x, y, z) => x) { | |
return new Proxy(value, { | |
defineProperty(target, prop, descriptor) { | |
target[prop] = handler(descriptor.value, prop, target); | |
return target; | |
}, | |
deleteProperty(target, prop) { | |
const value = handler(undefined, prop, target); | |
if (value !== undefined) { | |
target[prop] = value; | |
} | |
return target; | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment