使用Proxy和Reflect实现观察者模式

观察者模式(Observer Mode)定义:函数自动观察数据对象的模式,一旦对象有变化,函数就会自动执行

const observeObj = require('./observe.js')
const observe = observeObj.observe
const observable = Observe.observable

const person = observable({
    name: '张三',
    age: 20
})

function print (){
    console.log(`${person.name} ${person.age}`)
}

observe(print)
person.name = '丁丁'

 使用要求:

构建observeObj ,具备observe和observable两个方法

observable构建一个被观察的对象

observe为对象增加观察函数

 

封装的观察者对象代码如下:

const queuedObservers = new Set()
const observe = fn => queuedObservers.add(fn);
const observable = obj => new Proxy(obj, {set})

function set(target, key, value, receiver) {
    const result = Reflect.set(target, key, value, receiver);
    queuedObservers.forEach(observer => observer());
    return result;
}

exports = module.exports = {
    observe,
    observable
}

 

 


再深入一些,探索可以观察到深层改变的观察者模式,这里贴上代码

module.exports = (object, onChange) => {
    const handler = {
        get(target, property, receiver) {
            console.log('get')
            try {
                return new Proxy(target[property], handler);
            } catch (err) {
                console.log(err)
                return Reflect.get(target, property, receiver);
            }
        },
        set(target, property, descriptor) {
            console.log('set')
            onChange(target, property, descriptor);
            return Reflect.set(target, property, descriptor);
        },
        deleteProperty(target, property) {
            onChange();
            return Reflect.deleteProperty(target, property);
        }
    };

    return new Proxy(object, handler);
};

 

你可能感兴趣的:(Javascript)