畫一張watch的簡單工作流程圖:
把上文的 Dep,Oberver,Wather拿過來並做部分更改(增加收集依賴去重處理):
Dep代碼如下:
//標識當前的Dep id let uidep = 0 class Dep{ constructor () { this.id = uidep++ // 存放所有的監聽watcher this.subs = [] } //添加一個觀察者對象 addSub (Watcher) { this.subs.push(Watcher) } //依賴收集 depend () { //Dep.target 作用只有需要的才會收集依賴 if (Dep.target) { Dep.target.addDep(this) } } // 調用依賴收集的Watcher更新 notify () { const subs = this.subs.slice() for (let i = 0, l = subs.length; i < l; i++) { subs[i].update() } } } Dep.target = null const targetStack = [] // 為Dep.target 賦值
function pushTarget (Watcher) {
if (Dep.target) targetStack.push(Dep.target)
Dep.target = Watcher
}
function popTarget () {
Dep.target = targetStack.pop()
}