Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
zyy19930619 opened this issue Nov 18, 2019 · 0 comments
Open

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

zyy19930619 opened this issue Nov 18, 2019 · 0 comments

Comments

@zyy19930619
Copy link

zyy19930619 commented Nov 18, 2019

优化了一下,通过参数控制是否触发属性的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
    }
}
@zyy19930619 zyy19930619 changed the title 关于 watch 被重复订阅的问题 关于 watcher 被重复订阅的问题 Nov 18, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant