Vue 2.5データバインディング実現ロジック(一)全体ロジック
9106 ワード
概要では、Vue 2.5のデータバインドは主にオブジェクト属性のgetterとsetterのフックによって実現され,総じて初期化時にフックが確立され,データ更新時に対応するWatcherにコールバック関数を実行して更新を実行するよう通知するなどの操作が行われる.
具体的には、次のステップに分けます.インスタンスオブジェクトの初期化時にinitStateを実行する、props、dataのフックおよびそのオブジェクトメンバーのObserverを確立し、computed属性に対して、対応するすべてのWatcherを確立し、Objectを通過する.defineProperty vmオブジェクトにこのプロパティのgetterを設定します.同時に、対応するWatcher も、カスタムwatchに基づいて確立される.はマウント操作を実行し、マウント時にrender(レンダリング)に直接対応するWatcherを確立し、コンパイルテンプレートはrender関数を生成し、vm._を実行する.更新してDOMを更新します. は、その後、データが変更されるたびに、対応するWatcherにコールバック関数の実行を通知する.
ここの論理を本当に理解するには,まずDep,Observer,Watcherの3つのオブジェクトの役割と定義されたフック関数の中で何をしたのかを明らかにする必要がある.
Dep(dependency//依存)
場所:src/core/observer/dep.js
DepはWatcherに対応するデータ依存であり,この依存に関連するWatcherを保存するためのsubs配列もこのオブジェクトに存在する.そのメンバー関数の最も主要なものはdependとnotifyであり、前者はWatcherの依存を設定するために使用され、後者はこの依存に関連するWatcherにコールバック関数を実行するように通知するために使用される.
また、このクラスには静的メンバーtargetがあり、実行中のWatcherが格納されているグローバルスタックも見られます.
ここのスタックとスタックの出し方は言うまでもありません.
Observer
位置:src/core/observer/index.js
Observerは主にオブジェクトの変化を監視するために使用されます.例えばdataにオブジェクトメンバーが存在し、直接オブジェクトメンバーに属性を追加してもフック関数はトリガーされませんが、このオブジェクトはデータの一部であり、つまりオブジェクトが変化してもDOMが変化することを導きます.したがって、Observerを使用してオブジェクトの変更を監視し、変更時に関連するWatcherにコールバック関数を実行するように通知します.
ObserverにはDep,すなわち依存が存在することが分かる.
Observerを作成するときにobserve関数が使用されます
この関数は主にObserverを動的に返すために使用され、まずvalueがオブジェクトでなければ戻ると判断し、その後、オブジェクトにObserverがあるかどうかを検出し、ある場合は直接返します.そうしないと、新しくObserverをオブジェクトのob属性に保存します(コンストラクション関数で行を進みます).
Observerを作成するとき、OBが配列である場合、配列内の各メンバーに対してobserve関数を実行します.そうでない場合、オブジェクト属性ごとにdefineReactive関数を実行してget setフック関数を設定します.
Watcher
位置:src/core/observer/watcher.js
Watcherが構築時に伝達するパラメータが最も重要なのはexpOrFnであり、これはgetter関数であるか、あるいはgetter関数の文字列を生成するために使用することができるが、このgetter関数は前述のコールバック関数の一つであり、もう一つのコールバック関数はthisである.cb、この関数はvm.$しか使いません.watchによって生成されたWatcherが実行されます.getterはexpOrFnが文字列である場合、parsePathを実行してVueインスタンスオブジェクトに対応する熟知を取得します.
ここでget関数の役割は、getter関数を実行し、可能な戻り値(WatcherがrenderWatcherである場合、戻り値はundefined)をWatcherのvalue属性に割り当てることです.
update関数は、Depがnotify関数でWatcherに通知した後に実行される関数で、run関数が実行され、runでget関数が実行されます.
dependは、Watcherのdeps配列に保存されているすべての依存を関連付け、notifyで通知できるようにします.
defineReactive
位置:src/core/observer/index.js
この関数の主な役割は,あるオブジェクト属性のgetとsetフックを構築し,observe関数によってそのオブジェクトのObserverオブジェクトを取得し,データ依存Depを新規作成することである.getフック関数では、データ依存とWatcherの関連付けを処理し、setで依存notify関数を呼び出して関連付けられたWatcherにコールバック関数を実行するように通知します.
まとめ
これまでVueデータバインディングの大まかな論理はあまり整理されていなかったが、DepとWatcherがどのように連絡を結んだのか、異なるWatcherがいつ確立されたのか、Watcherのgetter関数が具体的にどのようなものなのか、これらの問題は後述する.
具体的には、次のステップに分けます.
ここの論理を本当に理解するには,まずDep,Observer,Watcherの3つのオブジェクトの役割と定義されたフック関数の中で何をしたのかを明らかにする必要がある.
Dep(dependency//依存)
場所:src/core/observer/dep.js
class Dep {
static target: ?Watcher;
id: number;
subs: Array;
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はWatcherに対応するデータ依存であり,この依存に関連するWatcherを保存するためのsubs配列もこのオブジェクトに存在する.そのメンバー関数の最も主要なものはdependとnotifyであり、前者はWatcherの依存を設定するために使用され、後者はこの依存に関連するWatcherにコールバック関数を実行するように通知するために使用される.
また、このクラスには静的メンバーtargetがあり、実行中のWatcherが格納されているグローバルスタックも見られます.
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()
}
ここのスタックとスタックの出し方は言うまでもありません.
Observer
位置:src/core/observer/index.js
class Observer {
value: any;
dep: Dep;
vmCount: number; // number of vms that has 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)) {
const augment = hasProto
? protoAugment
: copyAugment
augment(value, arrayMethods, arrayKeys)
this.observeArray(value)
} else {
this.walk(value)
}
}
/**
* Walk through each property 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], obj[keys[i]])
}
}
/**
* Observe a list of Array items.
*/
observeArray (items: Array) {
for (let i = 0, l = items.length; i < l; i++) {
observe(items[i])
}
}
}
Observerは主にオブジェクトの変化を監視するために使用されます.例えばdataにオブジェクトメンバーが存在し、直接オブジェクトメンバーに属性を追加してもフック関数はトリガーされませんが、このオブジェクトはデータの一部であり、つまりオブジェクトが変化してもDOMが変化することを導きます.したがって、Observerを使用してオブジェクトの変更を監視し、変更時に関連するWatcherにコールバック関数を実行するように通知します.
ObserverにはDep,すなわち依存が存在することが分かる.
Observerを作成するときにobserve関数が使用されます
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) {// Observer
ob = value.__ob__
} else if (
observerState.shouldConvert &&
!isServerRendering() &&
(Array.isArray(value) || isPlainObject(value)) &&
Object.isExtensible(value) &&
!value._isVue
) {
ob = new Observer(value)
}
if (asRootData && ob) {
ob.vmCount++
}
return ob
}
この関数は主にObserverを動的に返すために使用され、まずvalueがオブジェクトでなければ戻ると判断し、その後、オブジェクトにObserverがあるかどうかを検出し、ある場合は直接返します.そうしないと、新しくObserverをオブジェクトのob属性に保存します(コンストラクション関数で行を進みます).
Observerを作成するとき、OBが配列である場合、配列内の各メンバーに対してobserve関数を実行します.そうでない場合、オブジェクト属性ごとにdefineReactive関数を実行してget setフック関数を設定します.
Watcher
位置:src/core/observer/watcher.js
class Watcher {
vm: Component;
expression: string;
cb: Function;
id: number;
deep: boolean;
user: boolean;
lazy: boolean;
sync: boolean;
dirty: boolean;
active: boolean;
deps: Array;
newDeps: Array;
depIds: SimpleSet;
newDepIds: SimpleSet;
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
} 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 = function () {}
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 () {
......
}
/**
* Add a dependency to this directive.
*/
addDep (dep: Dep) {
......
}
/**
* Clean up for dependency collection.
*/
cleanupDeps () {
......
}
/**
* Subscriber interface.
* Will be called when a dependency changes.
*/
update () {
......
}
/**
* Scheduler job interface.
* Will be called by the scheduler.
*/
run () {
......
}
/**
* Evaluate the value of the watcher.
* This only gets called for lazy watchers.
*/
evaluate () {
......
}
/**
* Depend on all deps collected by this watcher.
*/
depend () {
......
}
/**
* Remove self from all dependencies' subscriber list.
*/
teardown () {
......
}
}
Watcherが構築時に伝達するパラメータが最も重要なのはexpOrFnであり、これはgetter関数であるか、あるいはgetter関数の文字列を生成するために使用することができるが、このgetter関数は前述のコールバック関数の一つであり、もう一つのコールバック関数はthisである.cb、この関数はvm.$しか使いません.watchによって生成されたWatcherが実行されます.getterはexpOrFnが文字列である場合、parsePathを実行してVueインスタンスオブジェクトに対応する熟知を取得します.
ここでget関数の役割は、getter関数を実行し、可能な戻り値(WatcherがrenderWatcherである場合、戻り値はundefined)をWatcherのvalue属性に割り当てることです.
update関数は、Depがnotify関数でWatcherに通知した後に実行される関数で、run関数が実行され、runでget関数が実行されます.
dependは、Watcherのdeps配列に保存されているすべての依存を関連付け、notifyで通知できるようにします.
defineReactive
位置: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
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()
}
if (setter) {
setter.call(obj, newVal)
} else {
val = newVal
}
childOb = !shallow && observe(newVal)
dep.notify()
}
})
}
この関数の主な役割は,あるオブジェクト属性のgetとsetフックを構築し,observe関数によってそのオブジェクトのObserverオブジェクトを取得し,データ依存Depを新規作成することである.getフック関数では、データ依存とWatcherの関連付けを処理し、setで依存notify関数を呼び出して関連付けられたWatcherにコールバック関数を実行するように通知します.
まとめ
これまでVueデータバインディングの大まかな論理はあまり整理されていなかったが、DepとWatcherがどのように連絡を結んだのか、異なるWatcherがいつ確立されたのか、Watcherのgetter関数が具体的にどのようなものなのか、これらの問題は後述する.