一般说到vue的数据绑定就是说通过Object.defineProperty
方法拦截属性,把data里面每个数据的读写改为getter和setter方法,当数据更新时通知视图更新。
mvvm数据双向绑定
- 即输入框当数据发生变化的时候,data数据同步变化,即view => Data的变化
- Data中的数据变化时,文本节点内容同步变化,即data => view的变化
要通过四个步骤,来实现数据的双向绑定
- 实现一个监听器Observer,用来劫持并监听属性的变化,如果属性发生变化就通知订阅者
- 实现一个订阅器,用来收集订阅者,对监听器Observer和订阅者Watcher进行统一管理
- 实现一个订阅者Watcher,可以收到属性的变化通知并执行相应的方法,从而更新视图
- 实现一个解析器Compile,可以解析每个相关指令,对模版数据和订阅器进行初始化
Object.defineProperty()
Object.defineProperty(obj, prop, descriptor)
descriptor可以定义数据存取。get和set。
mdn定义
数据存取符和数据描述符不能同时是两者。
监听器observer实现
1.字面量定义对象
首先我们定义一个对象
var person = {
name: 'xxx',
age: 24
}
我们访问name变量通过person.name但是当这个属性被修改的时候我们并不知情。
2.我们通过Object.defineProperty来定义一个对象
var val = 'tom';
var person = {};
Object.defineProperty(person, 'name', {
get() {
console.log('name 属性被读取了');
return val;
},
set(newVal) {
console.log('name 属性被修改了');
val = newVal;
}
})
person.name = 'xxx';
console.log(person.name)
结果
3. 改进方法
根据第二步我们已经可以监测到对象数据的修改了,但是对象的数据特别多的时候,我们要一个一个为属性去设置,代码会非常冗余,所以我们进行封装,从而让对象的所有数据都可被监测。
/**
* 循环遍历对象的每个属性
*/
function observable(obj) {
if (!obj || typeof obj !== 'object') {
return;
}
let keys = Object.keys(obj);
keys.forEach((key) => {
defineReactive(obj, key, obj[key]);
})
return obj;
}
// 将对象的属性用Object.defineProperty()进行设置
function defineReactive(obj, key, val) {
Object.defineProperties(obj, key, {
get() {
console.log(`${key} 属性被读取了。。。`);
return val;
},
set(newVal) {
console.log(`${key} 属性被读取了。。。`);
val = newVal;
}
})
}
通过封装我们直接定义Person
var person = observable({
name: 'xxx',
age: 24
})
订阅器Dep实现
实现了dep就可以在数据被读或者写的时候通知依赖该数据的视图更新了。为了方便我们将所有的依赖手机起来,一旦数据发生变化,就统一通知更新。数据变化为发布者,依赖对象为订阅者。
创建消息订阅器Dep:
function Dep() {
this.subs = [];
}
Dep.prototype = {
addSub: function(sub) {
this.subs.push(sub);
},
notify: function() {
this.subs.forEach(function(sub) {
sub.update();
})
}
}
Dep.target = null;
有了订阅器,我们再将defineReactive函数改造一下,向其植入订阅器。
defineReactive: function(data, key, val) {
var dep = new Dep();
Object.defineProperty(data, key, {
enumerable: true,
configurable: true,
get: function getter() {
if (Dep.target) {
dep.addSub(Dep.target);
}
return val;
},
set: function setter(newVal) {
if (newVal === val) {
return;
}
val = newVal;
dep.notify();
}
})
}
我们设计了一个订阅器Dep类,该类里面定义类一些属性和方法,这里需要特别注意它有一个静态属性Dep.target,这一个全局唯一watcher,因为在同已时间只有一个全局的watcher被计算,另外他的自身属性subs是Watcher的数组。
4.订阅者Watcher实现
我们要在get数据的时候设置上订阅者,在Dep.target存下订阅者,添加成功后再将其去掉就可以了,订阅者Watcher实现如下。
function Watcher(vm, exp, cb) {
this.vm = vm;
this.exp = exp;
this.cb = cb;
this.value = this.get(); // 将自己添加到订阅器的操作
}
Watcher.prototype = {
update: function() {
this.run();
},
run: function() {
var value = this.vm.data[this.exp];
var oldVal = this.value;
if (value !== oldVal) {
this.value = value;
this.cb.call(this.vm, value, oldVal);
}
},
get: function() {
Dep.target = this; // 全局变量 订阅者 赋值
var value = this.vm.data[this.exp] // 强制执行监听器里的get函数
Dep.target = null; // 全局变量 订阅者 释放
return value;
}
};
解析器compile实现
通过监听器Observer订阅器Dep和订阅者Watcher实现,其实就已经实现了一个双向绑定的例子,但是整个过程没有去解析dom节点,而是直接固定某个节点进行替换数据的,所以需要实现一个compile实现步骤:
- 解析模版指令,并替换模版数据,并初始化视图
- 将模版指令对应的的节点绑定对应的更新函数,初始化相应的订阅器
compileText: function(node, exp) {
var self = this;
var initText = this.vm[exp];
this.updateText(node, initText);
new Watcher(this.vm, exp, function (value) {
self.updateText(node, value);
})
}
vue源码数据双向绑定
监听器observer实现
observer的实现,主要是利用Object.defineProperty给数据添加了getter和setter。目的就是在我们数据变化的时候增加一些逻辑。
ininState
在vue初始化阶段,会进行初始ininState方法,他的定义在src/core/instance/state.js中。
export function initState (vm: Component) {
vm._watchers = []
const opts = vm.$options
if (opts.props) initProps(vm, opts.props)
if (opts.methods) initMethods(vm, opts.methods)
if (opts.data) {
initData(vm)
} else {
observe(vm._data = {}, true /* asRootData */)
}
if (opts.computed) initComputed(vm, opts.computed)
if (opts.watch && opts.watch !== nativeWatch) {
initWatch(vm, opts.watch)
}
}
initState方法主要是对props、methods、data、computed和watcher做了初始化操作,我们重点分析data
initData
function initData (vm: Component) {
let data = vm.$options.data
data = vm._data = typeof data === 'function'
? getData(data, vm)
: data || {}
if (!isPlainObject(data)) {
data = {}
process.env.NODE_ENV !== 'production' && warn(
'data functions should return an object:\n' +
'https://vuejs.org/v2/guide/components.html#data-Must-Be-a-Function',
vm
)
}
// proxy data on instance
const keys = Object.keys(data)
const props = vm.$options.props
const methods = vm.$options.methods
let i = keys.length
while (i--) {
const key = keys[i]
if (process.env.NODE_ENV !== 'production') {
if (methods && hasOwn(methods, key)) {
warn(
`Method "${key}" has already been defined as a data property.`,
vm
)
}
}
if (props && hasOwn(props, key)) {
process.env.NODE_ENV !== 'production' && warn(
`The data property "${key}" is already declared as a prop. ` +
`Use prop default value instead.`,
vm
)
} else if (!isReserved(key)) {
proxy(vm, `_data`, key)
}
}
// observe data
observe(data, true /* asRootData */)
}
data的初始化主要过程也是做两件事,一个是对定义data函数返回对象的遍历,通过proxy把每一个值vm.data.xxx都代理到vm.xxx,另一个是调用Observer方法观测整个data的变化,把data也变成响应式。
observer
observer的功能是用来监测数据的变化,定义在src/core/observer/index.js中。
export function observe (value: any, asRootData: ?boolean): Observer | void {
if (!isObject(value) || value instanceof VNode) {
return
}
let ob: Observer | void
if (hasOwn(value, '__ob__') && value.__ob__ instanceof Observer) {
ob = value.__ob__
} else if (
shouldObserve &&
!isServerRendering() &&
(Array.isArray(value) || isPlainObject(value)) &&
Object.isExtensible(value) &&
!value._isVue
) {
ob = new Observer(value)
}
if (asRootData && ob) {
ob.vmCount++
}
return ob
}
observer方法的作用就是给非VNode的对象类型数据添加一个Observer.如果已经添加过了则直接返回,否则在满足一定条件下去实例化一个observer对象。
Observer
Observer是一个类,他的作用是给对象属性添加getter和setter,勇于依赖收集和派发更新。
export class Observer {
value: any;
dep: Dep;
vmCount: number; // number of vms that have this object as root $data
constructor (value: any) {
this.value = value
this.dep = new Dep()
this.vmCount = 0
def(value, '__ob__', this)
if (Array.isArray(value)) {
if (hasProto) {
protoAugment(value, arrayMethods)
} else {
copyAugment(value, arrayMethods, arrayKeys)
}
this.observeArray(value)
} else {
this.walk(value)
}
}
/**
* Walk through all properties and convert them into
* getter/setters. This method should only be called when
* value type is Object.
*/
walk (obj: Object) {
const keys = Object.keys(obj)
for (let i = 0; i < keys.length; i++) {
defineReactive(obj, keys[i])
}
}
/**
* Observe a list of Array items.
*/
observeArray (items: Array<any>) {
for (let i = 0, l = items.length; i < l; i++) {
observe(items[i])
}
}
}
Observer的构造函数很简单,首先实例化Dep对象,接下来做value判断,对于数组会调用observerArray方法,否则对纯对象调用walk方法,可以看到observerArray是遍历数组再次调用observer方法,而walk是遍历对象的key调用defineReactive方法。
defineReactive
defineReactive的功能就是定义一个响应式对象,给对象动态添加getter和setter,他的定义在src/core/observer/index.js中
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()
}
})
}
defineReactive函数最开始初始化Dep对象的实例,接着拿到obj的属性描述符,然后对子对象递归调用observer方法,这样就保证了无论obj的结构多复杂,他的所有属性都可以变成响应式的对象,这样我们访问obj中一个嵌套较深的属性,也能触发getter和setter。
订阅器dep实现
订阅器Dep是整个getter依赖收集的核心,它的定义在src/core/observer/dep.js中
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()
}
}
}
Dep是一个class,他定义了一些属性和方法,这里需要特别注意的是它有一个静态属性target,这是全局唯一Watcher,这是一个非常巧妙的设计,因为在同一时间只能有一个全局Watcher被计算,另外它的自身属性subs也是watcher的数组,Dep实际上就是对Watcher的一种管理。
订阅者Watcher实现
定义在src/core/observer/watcher.js中。
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
}
}
}
watcher是一个class,在它的构造函数中,定义了一些和dep相关的属性,其中this.deps和this.newDeps表示Watcher实例持有的Dep实例的数组,而this.depIds和this.newDepIds分别代表this.deps和this.newDeps的idSet。
过程分析
当我们去实例化一个渲染watcher的时候,首先进入watcher的构造函数逻辑,然后会执行它的this.get()方法。进入get函数,会执行
pushTarget(this)
实际上就是把Dep.target赋值为当前的渲染watcher并压栈,接着又执行了
value = this.getter.call(vm, vm)
这个时候就触发了对象的getter
每个对象值的getter都持有一个dep,在触发getter的时候会调用dep.depend()方法,也会执行Dep.target.addDep(this)
刚才我们提到的Dep.target已经被赋值为渲染watcher,那么执行到addDep方法
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.addSub(this),那么就会执行this.subs.push(this),也就是把当前的watcher订阅到这个数据持有的dep的subs中,这个目的是为后续数据变化时能通知到哪些subs做准备,所以在vm._render()过程中,会触发数据的getter,这样实际就完成了一个依赖收集的过程。
当我们在组件中组件中对数据有修改,就会触发setter逻辑,最后调用watcher中的update方法:
update () {
/* istanbul ignore else */
if (this.lazy) {
this.dirty = true
} else if (this.sync) {
this.run()
} else {
queueWatcher(this)
}
}
这里会对于Watcher的不同状态,会执行不同逻辑。
课后作业
自己实现一个mvvm