Skip to content

Instantly share code, notes, and snippets.

@monkeymonk
Last active March 16, 2022 14:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save monkeymonk/8699c3c8bb2fb912c94b96bc08778b97 to your computer and use it in GitHub Desktop.
Save monkeymonk/8699c3c8bb2fb912c94b96bc08778b97 to your computer and use it in GitHub Desktop.
JavaScript Watch helper
/**
* @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