Vue源码解读-观察者模式
本文将讲解Vue的响应式原理,结合Vue的源码进行分析。响应式原理,也就是数据改变,页面展示也将重新渲染,实现页面无刷新更新。这里使用的是前端开发模式中的观察者模式:Vue中每个组件实例都对应一个 watcher 实例,它会在组件渲染的过程中把“接触”过的数据属性记录为依赖。之后当依赖项的 setter 触发时,会通知 watcher,从而使它关联的组件重新渲染。
了解了观察者模式后,Vue具体是怎么实现的呢,下面开始上源码。
入口在src/core/observer/index/js中的defineReactive方法
[code]export function defineReactive ( obj: Object, key: string, val: any, customSetter?: ?Function, shallow?: boolean ) { const dep = new Dep() const property = Object.getOwnPropertyDescriptor(obj, key) if (property && property.configurable === false) { return } // cater for pre-defined getter/setters const getter = property && property.get const setter = property && property.set if ((!getter || setter) && arguments.length === 2) { val = obj[key] } let childOb = !shallow && observe(val) Object.defineProperty(obj, key, { enumerable: true, configurable: true, get: function reactiveGetter () { const value = getter ? getter.call(obj) : val if (Dep.target) { dep.depend() if (childOb) { childOb.dep.depend() if (Array.isArray(value)) { dependArray(value) } } } return value }, set: function reactiveSetter (newVal) { const value = getter ? getter.call(obj) : val /* eslint-disable no-self-compare */ if (newVal === value || (newVal !== newVal && value !== value)) { return } /* eslint-enable no-self-compare */ if (process.env.NODE_ENV !== 'production' && customSetter) { customSetter() } // #7981: for accessor properties without setter if (getter && !setter) return if (setter) { setter.call(obj, newVal) } else { val = newVal } childOb = !shallow && observe(newVal) dep.notify() } }) }
方法接收五个参数,obj为要实现响应式的对象,key为具体响应的obj的key,val为obj中对应key的value,customSetter为一个函数,可以让用户自定义一个setter,shallow为是否为浅响应的bool值。
方法的开始就new了一个Dep,Dep是订阅者Watcher对应的数据依赖,来看下Dep的定义,在同级目录的dep.js。
[code]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 () { 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() } } }
首先这里维护了一个全局的uid,他是唯一的,新增一个Dep,就会自增,以此来标识这个Dep的唯一性。Dep维护了三个属性,target、id和subs。target是Watcher对象,是当前Dep的目标,subs是Dep订阅的Watcher数组。方法有新增和删除依赖,用以操作subs数组。depend方法是把Dep对象添加进Watcher中。notify便是遍历subs数组,按id顺序调用subs里每个Watcher的update方法。
看到这里肯定就会想知道Watcher又是怎样的一个对象,在同级目录的watcher.js中。
[code]let uid = 0 /** * A watcher parses an expression, collects dependencies, * and fires callback when the expression value changes. * This is used for both the $watch() api and directives. */ export default class Watcher { vm: Component; expression: string; cb: Function; id: number; deep: boolean; user: boolean; lazy: boolean; sync: boolean; dirty: boolean; active: boolean; deps: Array<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 ) { this.vm = vm if (isRenderWatcher) { vm._watcher = this } vm._watchers.push(this) // options 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 } this.cb = cb this.id = ++uid // uid for batching 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() : '' // parse expression for getter if (typeof expOrFn === 'function') { this.getter = expOrFn } else { 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 ) } } this.value = this.lazy ? undefined : this.get() } /** * Evaluate the getter, and re-collect dependencies. */ get () { pushTarget(this) let value const vm = this.vm try { value = this.getter.call(vm, vm) } catch (e) { if (this.user) { handleError(e, vm, `getter for watcher "${this.expression}"`) } else { throw e } } finally { // "touch" every property so they are all tracked as // dependencies for deep watching if (this.deep) { traverse(value) } popTarget() this.cleanupDeps() } return value } /** * Add a dependency to this directive. */ addDep (dep: Dep) { const id = dep.id if (!this.newDepIds.has(id)) { this.newDepIds.add(id) this.newDeps.push(dep) if (!this.depIds.has(id)) { dep.addSub(this) } } } /** * Clean up for dependency collection. */ 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 } /** * Subscriber interface. * Will be called when a dependency changes. */ update () { /* istanbul ignore else */ if (this.lazy) { this.dirty = true } else if (this.sync) { this.run() } else { queueWatcher(this) } } /** * Scheduler job interface. * Will be called by the scheduler. */ run () { if (this.active) { const value = this.get() if ( value !== this.value || // Deep watchers and watchers on Object/Arrays should fire even // when the value is the same, because the value may // have mutated. isObject(value) || this.deep ) { // set new value 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 the value of the watcher. * This only gets called for lazy watchers. */ evaluate () { this.value = this.get() this.dirty = false } /** * Depend on all deps collected by this watcher. */ depend () { let i = this.deps.length while (i--) { this.deps[i].depend() } } /** * Remove self from all dependencies' subscriber list. */ teardown () { if (this.active) { // remove self from vm's watcher list // this is a somewhat expensive operation so we skip it // if the vm is being destroyed. if (!this.vm._isBeingDestroyed) { remove(this.vm._watchers, this) } let i = this.deps.length while (i--) { this.deps[i].removeSub(this) } this.active = false } } }
代码片段较长,这里一个function一个function的解读。
Watcher是什么,注释写的很清楚,大概意思就是观察者解析表达式、收集依赖、当数据改变时调用回调函数。他被用于$watch()的api和指令。和Dep一样,也维护了一个uid。可以看到Watcher的属性有很多,能从字面上理解的只有一部分:vm就是组件对象,expression是表达式,deep是深观察的标记位,lazy是否为懒加载,active是否启用,deps是数据依赖Dep的数组,newDeps为新增的数据依赖Dep数组,depIds和newDepIds分别为对应的Dep的id集合,getter和value自不必说。
先来看构造函数:
[code] constructor ( vm: Component, expOrFn: string | Function, cb: Function, options?: ?Object, isRenderWatcher?: boolean ) { this.vm = vm if (isRenderWatcher) { vm._watcher = this } vm._watchers.push(this) // options 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 } this.cb = cb this.id = ++uid // uid for batching 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() : '' // parse expression for getter if (typeof expOrFn === 'function') { this.getter = expOrFn } else { 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 ) } } this.value = this.lazy ? undefined : this.get() }
乍一看写了挺多,其实没啥。构造函数接收5个参数,vm为组件,expOrFn为表达式或者函数,用作Watcher的getter,cb是个函数,暂时还不知道是个啥,options为参数对象,isRenderWatcher标记位看代码的作用是确认该Watcher是否为组件的唯一Watcher。下面就是将接收的参数设置到Watcher的属性中。
接着来看get的定义。
[code]/** * Evaluate the getter, and re-collect dependencies. */ get () { pushTarget(this) let value const vm = this.vm try { value = this.getter.call(vm, vm) } catch (e) { if (this.user) { handleError(e, vm, `getter for watcher "${this.expression}"`) } else { throw e } } finally { // "touch" every property so they are all tracked as // dependencies for deep watching if (this.deep) { traverse(value) } popTarget() this.cleanupDeps() } return value }
这里涉及到pushTarget、popTarget、traverse和cleanupDeps。
[code]const targetStack = [] export function pushTarget (target: ?Watcher) { targetStack.push(target) Dep.target = target } export function popTarget () { targetStack.pop() Dep.target = targetStack[targetStack.length - 1] }
这两个方法在observer/dep.js中,一个是给Dep的target赋值Watcher并在targetStack数组中push,一个是pop掉targetStack并让target指向stack里的前一个。
[code]const seenObjects = new Set() /** * Recursively traverse an object to evoke all converted * getters, so that every nested property inside the object * is collected as a "deep" dependency. */ export function traverse (val: any) { _traverse(val, seenObjects) seenObjects.clear() } function _traverse (val: any, seen: SimpleSet) { let i, keys const isA = Array.isArray(val) if ((!isA && !isObject(val)) || Object.isFrozen(val) || val instanceof VNode) { return } if (val.__ob__) { const depId = val.__ob__.dep.id if (seen.has(depId)) { return } seen.add(depId) } if (isA) { i = val.length while (i--) _traverse(val[i], seen) } else { keys = Object.keys(val) i = keys.length while (i--) _traverse(val[keys[i]], seen) } }
traverse在observer/traverse.js中,其实就是递归遍历val,这里用到val.__ob__的判断,只要val被观察了,它就会有__ob__属性,这里其实就是判断val是否被观察过了。
[code] /** * Clean up for dependency collection. */ 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 }
cleanupDeps为watcher的一个方法,就是清除所有依赖,并更新了相关属性。
这样看来get方法就是收集对象的依赖,添加到依赖中,实现订阅。
接下来看Watcher的addDep方法。
[code] /** * Add a dependency to this directive. */ addDep (dep: Dep) { const id = dep.id if (!this.newDepIds.has(id)) { this.newDepIds.add(id) this.newDeps.push(dep) if (!this.depIds.has(id)) { dep.addSub(this) } } }
该方法用于向当前指令增加一个数据依赖,这里用到了Dep的id去判断是否已存在,避免重复添加。
接着就是当数据更新时调用的update方法了:
[code] /** * Subscriber interface. * Will be called when a dependency changes. */ update () { /* istanbul ignore else */ if (this.lazy) { this.dirty = true } else if (this.sync) { this.run() } else { queueWatcher(this) } }
如果是懒加载,就把dirty设为true,在下一个tick时再更新,如果是同步的,就调用run方法,立即执行更新,异步就调用queueWatcher方法,把其添加到队列中,下一个tick时一起更新。
先看run方法:
[code] /** * Scheduler job interface. * Will be called by the scheduler. */ run () { if (this.active) { const value = this.get() if ( value !== this.value || // Deep watchers and watchers on Object/Arrays should fire even // when the value is the same, because the value may // have mutated. isObject(value) || this.deep ) { // set new value 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) } } } }
如果Watcher是启用状态,就更新数据,并且调用cb方法,此时就明白了,cb方法就是更新组件触发重新渲染的方法。
再看queueWatcher方法,此方法在scheduler.js中:
[code]export function queueWatcher (watcher: Watcher) { const id = watcher.id if (has[id] == null) { has[id] = true if (!flushing) { queue.push(watcher) } else { // if already flushing, splice the watcher based on its id // if already past its id, it will be run next immediately. let i = queue.length - 1 while (i > index && queue[i].id > watcher.id) { i-- } queue.splice(i + 1, 0, watcher) } // queue the flush if (!waiting) { waiting = true if (process.env.NODE_ENV !== 'production' && !config.async) { flushSchedulerQueue() return } nextTick(flushSchedulerQueue) } } }
queue就是一个Watcher的数组,如果还没刷新,就添加进去,如果已经刷新了,就等到下一个tick再去做。
接着看Watcher的evaluate方法:
[code] /** * Evaluate the value of the watcher. * This only gets called for lazy watchers. */ evaluate () { this.value = this.get() this.dirty = false }
就是对于懒加载来说,用户可能希望立即更新,就可以调用这个方法,立即获得最新值,并且更新并渲染。
[code] /** * Depend on all deps collected by this watcher. */ depend () { let i = this.deps.length while (i--) { this.deps[i].depend() } }
depend就是调用deps数组里所有Dep的depend方法。
最后一个Watcher的方法tearDown:
[code] /** * Remove self from all dependencies' subscriber list. */ teardown () { if (this.active) { // remove self from vm's watcher list // this is a somewhat expensive operation so we skip it // if the vm is being destroyed. if (!this.vm._isBeingDestroyed) { remove(this.vm._watchers, this) } let i = this.deps.length while (i--) { this.deps[i].removeSub(this) } this.active = false } } }
应该是用于销毁所有的数据依赖订阅列表,然后把active设为false。这样就不会再触发更新渲染了。
至此,所有与响应式原理相关的Vue源码解读完毕。
- 基于AIDL的 Activity、Service跨进程观察者模式实现与源码解读(附github源码)
- 从vue源码看观察者模式
- azkaban源码解读(二):观察者模式在job执行过程中事件监听应用
- 从vue源码看观察者模式
- 浅析从vue源码看观察者模式
- RxJava 源码解读分析 观察者模式
- java源码实现观察者模式
- Java8 观察者模式详解 jdk实现源码分析
- Android设计模式系列(2)--SDK源码之观察者模式
- vue源码解读预热-0
- Netty源码解读(四)Netty与Reactor模式
- Vue源码解读——实现一个双向绑定(Object.defineProperty与observe)
- 看JSlider的jdk源码学观察者模式
- vuex 源码解读
- Netty源码解读——Netty与Reactor模式
- Android设计模式系列(2)--SDK源码之观察者模式
- Android设计模式系列(2)--SDK源码之观察者模式
- 源码解析RxBus实现观察者模式
- 从vue的组件传值着手浅谈观察者模式
- vue双向绑定及观察者模式详解