// 当前 Dep 的 id,唯一
let uid = 0
/**
* A dep is an observable that can have multiple
* directives subscribing to it.
*/
export default class Dep {
static target: ?Watcher;
id: number;
subs: Array<Watcher>;
constructor () {
// 当前 Dep 的 id,唯一
this.id = uid++
// 监听者列表
this.subs = []
}
// 添加监听者
addSub (sub: Watcher) {
this.subs.push(sub)
}
// 移除监听
removeSub (sub: Watcher) {
remove(this.subs, sub)
}
// 依赖收集,双向收集,目的是为了保持一致性
depend () {
if (Dep.target) {
Dep.target.addDep(this)
}
}
// 通知依赖项响应
notify () {
// stabilize the subscriber list first
// 浅拷贝,用于可能的数据处理
const subs = this.subs.slice()
if (process.env.NODE_ENV !== 'production' && !config.async) {
// subs aren't sorted in scheduler if not running async
// we need to sort them now to make sure they fire in correct
// order
subs.sort((a, b) => a.id - b.id)
}
// 通知监听者响应
for (let i = 0, l = subs.length; i < l; i++) {
subs[i].update()
}
}
}
// The current target watcher being evaluated.
// This is globally unique because only one watcher
// can be evaluated at a time.
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]
}