<!DOCTYPE html><script>
let handlers = Symbol('-_-');
function makeObservable(target) {
// 1. Initialize handlers store
target[handlers] = [];
// Store the handler function in array for future calls
target.qwer = 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;
}
});
}
let user = {};
user = makeObservable(user);
user.qwer((key, value) => {
alert(`SET ${key}=${value}`);
});
user.name = "John";
</script>
Если первую строку кода заменить на
let handlers;
- ничего не изменится.