watcher.update();
})
}
}
module.exports = Dep;
这里的每个依赖就是一个Watcher 。
看看如何定义 Watcher
这里每一个 Watcher 都会有一个唯一的id号,它拥有一个表达式和一个回调函数 。
比如 表达式 a +b ; 会在get 计算时 访问 a 与 b , 由于 JavaScript是单线程,任一时刻只有一处JavaScript代码在执行, 用Dep.target 作为一个全局变量来表示当前 Watcher 的表达式,然后通过 compute 访问 a ,b ,触发 a 与b 的getter,在 getter 里面将 Dep.target 添加为依赖 。
一旦 a 与 b 的set 触发,调用 update 函数,更新依赖的值 。
var uid = 0;
class Watcher {
constructor(viewModel, exp, callback) {
this.viewModel = viewModel;
this.id = uid++;
this.exp = exp;
this.callback = callback;
this.oldValue = "";
this.update();
} get() {
Dep.target = this;
var res = this.compute(this.viewModel, this.exp);
Dep.target = null;
return res;
}
update() {
var newValue = this.get();
if (this.oldValue === newValue) {
return;
}
// callback 里进行Dom 的更新操作
this.callback(newValue, this.oldValue);
this.oldValue = newValue;
}
compute(viewModel, exp) {
var res = replaceWith(viewModel, exp);
return res;
}
}
module.exports = Watcher;
由于当前表达式需要在 当前的model下面执行,所以 采用replaceWith 函数来代替 with ,具体可以查看另一篇随笔javascript 中 with 的替代语法。
通过get 添加依赖
Object.defineProperty(vm, key, {
get: function() {
var watcher = Dep.target;
if (watcher && !dep.dependences[watcher.id]) {
dep.addDep(watcher);
}
return value;
},
set: function(newVal) {
if (value != newVal) {
if (newVal && typeof newVal === "object") {
self.walk(newVal);
}
value = newVal;
dep.notify();
}
}
})这种添加依赖的方式实在太巧妙了 。
这里我画了一个图来描述

最后通过一段代码简单测试一下
const Observer = require('./Observer.js');
const Watcher = require('./watcher.js');
var data = {
a: 10,
b: {
c: 5,
d: {
e: 20,
}
}
}var observe = new Observer(data);
var watcher = new Watcher(data, "a+b.c", function(newValue, oldValue) {
console.log("new value is " + newValue);
console.log("oldValue is " + oldValue);










