vue 双向绑定中观察者模式

在数据劫持之外最重要的部分就是Dep和Watcher,这其实是一个观察者模式。
用最简单的代码实现以下Vue的观察者模式:
	通过watcher.evaluate()将自身实例赋值给Dep.target
	调用dep.depend()将dep实例将watcher实例push到dep.subs中
	通过数据劫持,在调用被劫持的对象的set方法时,调用dep.subs中所有的watcher.update()
// 观察者
class Dep {
    
    
    constructor() {
    
    
        this.subs = []
    }
    
    addSub(sub) {
    
    
        this.subs.push(sub)
    }
    
    depend() {
    
    
        if (Dep.target) {
    
     
            Dep.target.addDep(this);	//添加每次实例化watcher后绑定到Dep.target上的watcher实例
        }
    }
    
    notify() {
    
    
        this.subs.forEach(sub => sub.update())
    }
}

// 被观察者
class Watcher {
    
    
    constructor(vm, expOrFn) {
    
    
        this.vm = vm;
        this.getter = expOrFn;
        this.value;
    }

    get() {
    
    
        Dep.target = this;		
        
        var vm = this.vm;
        var value = this.getter.call(vm, vm);
        return value;
    }

    evaluate() {
    
    
        this.value = this.get();
    }

    addDep(dep) {
    
    
        dep.addSub(this);
    }
    
    update() {
    
    
        console.log('更新, value:', this.value)
    }
}

// 观察者实例
var dep = new Dep();

//  被观察者实例
var watcher = new Watcher({
    
    x: 1}, (val) => val);
watcher.evaluate();

// 观察者监听被观察对象
dep.depend()

dep.notify()

猜你喜欢

转载自blog.csdn.net/weixin_43294560/article/details/121476585