/* @flow */
import {
warn,
remove,
isObject,
parsePath,
_Set as Set,
handleError,
noop
} from '../util/index'
import { traverse } from './traverse'
import { queueWatcher } from './scheduler'
import Dep, { pushTarget, popTarget } from './dep'
import type { SimpleSet } from '../util/index'
let uid = 0
/**
* watcher解析一个表达式,收集依赖,
* 并在表达式值更改时触发回调。
* 这用于$ watch()api和指令。
*/
export default class Watcher {
vm: Component;
expression: string; // 每一个DOM attr对应的string
cb: Function; // update时候的回调函数
id: number;
deep: boolean;
user: boolean; // 判断是否是user watcher
lazy: boolean; // 判断是否是computed watcher
sync: boolean; // 判断是否同步执行,false就放到下一个tick里排队执行
dirty: boolean;
active: boolean;
deps: Array<Dep>; // Dep数组,收集的依赖
newDeps: Array<Dep>;
depIds: SimpleSet;
newDepIds: SimpleSet;
before: ?Function;
getter: Function; // 收集依赖,求值
value: any;
constructor (
vm: Component,
expOrFn: string | Function,
cb: Function,
options?: ?Object,
isRenderWatcher?: boolean // 判断是否是 render watcher
) {
// 传进来的对象 例如Vue
this.vm = vm
if (isRenderWatcher) {
vm._watcher = this // 如果是render watcher,就保存在vm._watcher
}
// vm._watchers 数组用于存储组件实例 vm 的所有 watchers
vm._watchers.push(this)
// 用户和vue提供的一些配置项
if (options) {
this.deep = !!options.deep
this.user = !!options.user
this.lazy = !!options.lazy
this.sync = !!options.sync
this.before = options.before
} else {
this.deep = this.user = this.lazy = this.sync = false
}
// 在Vue中cb是更新视图的核心,调用diff并更新视图的过程
this.cb = cb
this.id = ++uid // uid 用来批处理
this.active = true
this.dirty = this.lazy // for lazy watchers
this.deps = []
this.newDeps = []
this.depIds = new Set()
this.newDepIds = new Set()
this.expression = process.env.NODE_ENV !== 'production'
? expOrFn.toString()
: ''
// 把表达式解析成getter
if (typeof expOrFn === 'function') {
// render watcher 的 getter 通常为 updateComponent 方法
this.getter = expOrFn
} else {
// 初始化 user watcher 的 getter
this.getter = parsePath(expOrFn)
if (!this.getter) {
this.getter = noop
process.env.NODE_ENV !== 'production' && warn(
`Failed watching path: "${expOrFn}" ` +
'Watcher only accepts simple dot-delimited paths. ' +
'For full control, use a function instead.',
vm
)
}
}
// 设置Dep.target的值,依赖收集时的watcher对象
// 在构造函数的最后,执行 this.get(),首次收集依赖。所以说在 new Watcher 时,马上就会收集一次依赖
this.value = this.lazy
? undefined
: this.get()
}
/**
* 触发getter,获得getter的值,并重新收集依赖
*/
get () {
// 设置Dep.target值,用以依赖收集
pushTarget(this)
let value
const vm = this.vm
try {
// 执行this.vm.getter(this.vm),就是为了触发getter,
// 从而把vm放到dep里,收集依赖
// 对于不同类型的 watcher,它们的 getter 不尽相同
value = this.getter.call(vm, vm)
} catch (e) {
if (this.user) {
handleError(e, vm, `getter for watcher "${this.expression}"`)
} else {
throw e
}
} finally {
// 当依赖被标记为deep的时候,把每一个属性都touch一下
if (this.deep) {
traverse(value)
}
popTarget()
this.cleanupDeps()
}
return value
}
/**
* 添加一个依赖关系到Deps集合中
* 在dep.depend()中调用的是Dep.target.addDep()
*/
addDep (dep: Dep) {
// 去重
const id = dep.id
// 只有第一次触发getter时才会收集依赖
if (!this.newDepIds.has(id)) {
// newDepIds和newDeps记录watcher实例所用到的dep
this.newDepIds.add(id)
this.newDeps.push(dep)
if (!this.depIds.has(id)) {
//收集watcher 每次data数据 set
//时会遍历收集的watcher依赖进行相应视图更新或执行watch监听函数等操作
dep.addSub(this)
}
}
}
/**
* 清除收集的依赖
*/
cleanupDeps () {
// 移除所有观察者对象
let i = this.deps.length
while (i--) {
const dep = this.deps[i]
if (!this.newDepIds.has(dep.id)) {
dep.removeSub(this)
}
}
let tmp = this.depIds
this.depIds = this.newDepIds
this.newDepIds = tmp
this.newDepIds.clear()
tmp = this.deps
this.deps = this.newDeps
this.newDeps = tmp
this.newDeps.length = 0
}
/**
* 订阅者接口
* 将会在一个依赖发生改变时被触发
* dep.notify的时候会逐个调用watcher的update方法
*/
update () {
/* istanbul ignore else */
if (this.lazy) {
this.dirty = true
} else if (this.sync) {
this.run()
} else {
queueWatcher(this)
}
}
/**
* 调度者工作接口
* 将被调度者回调
*/
run () {
if (this.active) {
const value = this.get()
if (
value !== this.value ||
// 即便值相同,拥有Deep属性的观察者以及在对象/数组上的观察者应该被触发更新,
// 因为它们的值可能发生改变
isObject(value) ||
this.deep
) {
// 设置新值
const oldValue = this.value
this.value = value
// 触发回调渲染视图
if (this.user) {
try {
this.cb.call(this.vm, value, oldValue)
} catch (e) {
handleError(e, this.vm, `callback for watcher "${this.expression}"`)
}
} else {
this.cb.call(this.vm, value, oldValue)
}
}
}
}
/**
* 获取观察者的值
* 这仅适用于懒惰的观察者
*/
evaluate () {
this.value = this.get()
this.dirty = false
}
/**
* 收集该watcher的所有deps依赖
*/
depend () {
let i = this.deps.length
while (i--) {
this.deps[i].depend()
}
}
/**
* 将自身从所有依赖收集订阅列表删除
*/
teardown () {
if (this.active) {
// 从vm实例的观察者列表中将自身移除,
// 由于该操作比较耗费资源,
//所以如果vm实例正在被销毁则跳过该步骤
if (!this.vm._isBeingDestroyed) {
remove(this.vm._watchers, this)
}
let i = this.deps.length
while (i--) {
this.deps[i].removeSub(this)
}
this.active = false
}
}
}
这是一个统一的Watcher的类,在类里面通过lazy,user,和isRenderWatcher三个标识来区别。通常user watcher是用户自己创建的watcher,renderWatcher是Vue自己在初始化的时候,初始化数据,创建watcher,而computedWatcher则是用lazy来表示用户在computed里写的变量。它们都使用了同一个Watcher类。
根据Dep类来看,Watcher需要完成2个需求:
- 在dep.depend()中调用的是Dep.target.addDep(),把自己放到Dep中
- dep.notify()的时候调用watcher.update()方法,对视图进行更新
在vue初始化的时候,就会初始化watcher,createWatcher方法里,调用vm.$watch,在$watch中new一个Watcher类来初始化
const watcher = new Watcher(vm, expOrFn, cb, options)