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
}
}
複製代碼