vue双向数据绑定vue
watcher怎么连接observe和compile?express
getter方法的时候,判断存不存在dep.target,若是存在,就将dep.target添加到dep.addsub;
setter方法的时候,调用dep.notify(),遍历dep里面的订阅者,而且执行update方法; 消息订阅器bash
export default class Dep {
constructor() {
this.subs = [];
};
addSub(sub) {
this.subs.push(sub);
};
notify() {
this.subs.forEach(sub => sub.update());
}
}
复制代码
export default class Watcher {
constructor(vm, expOrFn, cb) {
this.cb = cb
this.vm = vm
//此处简化.要区分fuction仍是expression,只考虑最简单的expression
this.expOrFn = expOrFn
this.value = this.get()
}
update() {
this.run()
}
run() {
const value = this.get()
if (value !== this.value) {
this.value = value
this.cb.call(this.vm)
}
}
get() {
Dep.target = this
//此处简化。。要区分fuction仍是expression
const value = this.vm._data[this.expOrFn]
Dep.target = null
return value
}
}
复制代码