我们先打开文件src/core/observer/dep.js
。
代码如下:
/**
* 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 () {
this.id = uid++
this.subs = []
}
// 添加监听者
addSub (sub: Watcher) {
this.subs.push(sub)
}
// 删除监听者
removeSub (sub: Watcher) {
remove(this.subs, sub)
}
// 如果`target`存在就会继续添加监听
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() // 执行更新
}
}
}
可以看到有如下几个方法:
constructor
构造函数
addSub
添加监听
removeSub
删除监听
depend
如果target
存在就会继续添加监听
notify
通知监听者
网友评论