1、用Reflect实现观察者模式
const person = observable({ // persion观察目标
name: '张三',
age: 20
});
function print() {
console.log(`${person.name}, ${person.age}`)
}
observe(print); //print观察者
person.name = '李四';
// 输出
// 李四, 20
const queuedObservers = new Set(); // set集合
const observe = fn => queuedObservers.add(fn); //所有函数都放到集合
const observable = obj => new Proxy(obj, {set}); //Proxy代理
function set(target, key, value, receiver) {
const result = Reflect.set(target, key, value, receiver);
queuedObservers.forEach(observer => observer());
return result;
}
网友评论