在数据劫持之外最重要的部分就是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);
}
}
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()