JavaScript | Proxy实现观察者模式

关于“观察者模式”(摘自维基百科,对观察者模式的介绍)

The observer pattern is a software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods.

It is mainly used to implement distributed event handling systems, in “event driven” software. Most modern languages such as C# have built in “event” constructs which implement the observer pattern components, for easy programming and short code.

The observer pattern is also a key part in the familiar model–view–controller (MVC) architectural pattern. The observer pattern is implemented in numerous programming libraries and systems, including almost all GUI toolkits.

代码示例如下

/**
*  Proxy 实现观察者模式,监听对象数据的变化
*/

// 定义观察者
const observer = new Set();
observer.add((key) => console.log(`执行观察者1:${key} 的值发生了变化`));
observer.add((key) => console.log(`执行观察者2:${key} 的值发生了变化`));

// 定义 observable函数
// 该函数返回一个原始对象的 Proxy 代理,拦截赋值操作,并触发观察者的各个函数。
const observable = obj => new Proxy(obj, {
    set(target, key, value, receiver) {
        if (target[key] === value) return;
        // 执行观察者函数集
        observer.forEach(fn => fn(key));
        // 赋值并返回
        return Reflect.set(target, key, value, receiver);
    },
    get(target, key) {
        console.log(`用户读取了 ${key} 的值`);
        return target[key];
    }
});

// 测试 观察目标
let person = observable({name: 'Lucy', age: 20});

在谷歌浏览器测试结果
JavaScript | Proxy实现观察者模式_第1张图片

你可能感兴趣的:(JavaScript)