之前的章节讲解完了Vue从BeforeCreated到mount的过程,这里我们对Vue的事件的监听进行处理,首先这里介绍的是依赖类Dep。
数据成员
(1)静态的监视器对象target。
(2)数值类型的Dep对象的编号的id。
(3)数组类型的监视器数组subs。
成员函数
(1)构造函数:设置Dep对象的id号,并更新全局的iD号,以及初始化subs的数组的值为空。
(2)addSub方法:向Dep实例中的subs数组中添加监视器对象。
(3)removeSub方法:删除Dep实例中subs数组中指定的监视器对象。
(4)depend方法:调用Dep实例的Target属性的addDep方法添加将此Dep实例添加至Dep的Target的依赖中。
(5)notify方法:变量Dep的subs数组中的监视器并调用其的update方法。
全局变量和函数
(1)uid:用于标记Dep实例的标识符。
(2)targetStack:target数组。
(3)Dep.target:初始化Dep实例的target为空数组。
(3)pushTarget方法:如果Dep实例的target的值为真向targetStack数组尾部添加此监视器,设置当前Dep实例的target为传入的监视器。
(4)popTarget方法:从targetStack数组中的头部取出一个监视器对象赋值给Dep实例的target属性。
/* @flow */
import type Watcher from './watcher'
import { remove } from '../util/index'
let uid = 0
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)
}
depend () {
if (Dep.target) {
Dep.target.addDep(this)
}
}
notify () {
// stabilize the subscriber list first
const subs = this.subs.slice()
for (let i = 0, l = subs.length; i < l; i++) {
subs[i].update()
}
}
}
//
Dep.target = null
const targetStack = []
export function pushTarget (_target: Watcher) {
if (Dep.target) {
targetStack.push(Dep.target)
}
Dep.target = _target
}
export function popTarget () {
Dep.target = targetStack.pop()
}