# Dep
let uid = 0
export default class Dep {
static target?: Watcher;
id: number
subs: Array<Watcher>
constructor () {
this.id = uid++
this.subs = []
}
// 添加wathcer
addSub (watcher: Watcher) {
this.subs.push(watcher)
}
removeSub (sub: Wathcer) {
remove(this.subs, sub)
}
// 向 wathcer 中添加 dep, 同时 dep 也会讲当前的 Dep.target 的 wathcer 添加进 subs
depend () {
if (Dep.target) {
Dep.target.addDep(this)
}
}
// 通过 subs 中的 wathcer.update() 方法
notify () {
// 拷贝
const subs = this.subs.slice();
if (process.env.NODE_ENV !== 'production' && !config.async) {
// 如果 watcher 不是异步 (sync: true) 则需要进行排序再执行update
subs.sort((a, b) => a.id - b.id)
}
for (let i = 0, l = subs.length; i< l; i++) {
subs[i].update()
}
}
}
/**
* 保存当前正在执行的 wathcer
*/
Dep.target = null
const targetStack = [] // 栈
export function pushTarget (target?: Watcher) {
targetStack.push(target)
Dep.target = target
}
export function popTarget () {
targetStack.pop()
Dep.target = targetStack[targetStack.length -1]
}