ES6 series ----- Getting the Proxy implement the Observer pattern

    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;
  1. First, we define a function for storing observe to be triggered.
  2. 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.
  3. 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.

Guess you like

Origin www.cnblogs.com/LHLVS/p/11039245.html