Skip to content

关于 watcher 被重复订阅的问题 #45

@zyy19930619

Description

@zyy19930619

优化了一下,通过参数控制是否触发属性的get , 把订阅者(watcher)添加到订阅器(keyDep)中。这样会比较好理解, 另外个人觉得 在闭包中保存 dep 对新手不太好理解, 可以提取出来 用统一的发布订阅中心维护 订阅器和相应的订阅者

observer.js
 get: function () {
         KeyDep.current_watcher && keydep.addSub(KeyDep.current_watcher)
         return val;
 },

watcher.js
function Watcher(vm,attr_val,cb){ 
    this.vm = vm;
    this.attr_val = attr_val;
    this.cb = cb;
    this.value = this.get(this) //触发get 把 自己(订阅者)添加到 相应的订阅器中
}
Watcher.prototype = {
    contructor: Watcher,
    update(){
        var newValue = this.get(null); //再次触发get 不再往 相应的订阅器中 添加自己(订阅者)
        var oldValue = this.value;
        if(newValue !== oldValue){ 
            this.value = newValue;
            this.cb.call(this.vm,newValue,oldValue)
        }
    },
    get(_this){
        KeyDep.current_watcher = _this;
        var value = compileUtil._getVMVal(this.vm,this.attr_val);
        KeyDep.current_watcher = null;
        return value
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions