Automatic mode change means the observer to observe a data object function, once the object has changed, the function will be executed automatically.
It defines a dependent relationship of many, we use Proxy to implement a simple observer mode (PS: We think beginners
Observer mode == publish-subscribe model, in fact they are a bit different).
example:
const callbacks = new Set();
const observe = fn => callbacks.add(fn);
const observable = obj => new Proxy(obj, {set});
function set (target, key, value, receiver) {
const result = Reflect.set(target, key, value, receiver);
callbacks.forEach(observe => observe());
return result;
}
// 一个可观察的对象
const person = observable({name: 'liu', age: 18});
function change() {
console.log(`${person.name} is ${person.age}`);
}
observe(change);
person.age = 19;
- First, we define a function for storing observe to be triggered.
- Then define a function to set the value of observable objects do layer proxy, intercepting assignment, Reflect.set used to complete the default behavior of the set value, then the trigger function.
- Whenever an object set method calls inside the object, it will traverse the trigger we added to the callbacks in the callback function.
Print result: when age changes: print out
So we implemented a simple observer mode.