// 添加订阅,相当于 dep.subs.push(this)
dep.addSub(this);
this.depIds.add(id);
}
};
function parseGetter(exp) {
if (/[^w.$]/.test(exp)) {
return;
}
let exps = exp.split(".");
return function(obj) {
for (let i = 0; i < exps.length; i++) {
if (!obj)
return;
obj = obj[exps[i]];
}
return obj;
};
}
最后还差一部分,即 Dep 通知变化后,Watcher 的处理,具体的函数调用流程是这样的:dep.notify() -> sub.update(),直接上代码:
Watcher.prototype.update = function() {
this.run();
};Watcher.prototype.run = function() {
let value = this.get();
let oldVal = this.value;
if (value !== oldVal) {
this.value = value;
// 调用回调函数更新视图
this.cb.call(this.$vm, value, oldVal);
}
};
结语
到这就算写完了,本人水平有限,若有不足之处欢迎指出,一起探讨。
参考资料
https://github.com/DMQ/mvvm










