Created
June 18, 2020 06:16
-
-
Save ivan-stepaniuk/1580a51b7e583994cbb983864efaf109 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| 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