Skip to content

Instantly share code, notes, and snippets.

@ivan-stepaniuk
Created June 18, 2020 06:16
Show Gist options
  • Select an option

  • Save ivan-stepaniuk/1580a51b7e583994cbb983864efaf109 to your computer and use it in GitHub Desktop.

Select an option

Save ivan-stepaniuk/1580a51b7e583994cbb983864efaf109 to your computer and use it in GitHub Desktop.
function makeObservable(target) {
// 1. Initialize handlers store
target[handlers] = [];
// Store the handler function in array for future calls
target.observe = function (handler) {
this[handlers].push(handler);
};
// 2. Create a proxy to handle changes
return new Proxy(target, {
set(target, property, value, receiver) {
let success = Reflect.set(...arguments); // forward the operation to object
if (success) { // if there were no error while setting the property
// call all handlers
target[handlers].forEach(handler => handler(property, value));
}
return success;
}
});
}
element = makeObservable(element);
element.observe((key, value) => {
console.warn(`SET ${key}=${value}`);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment