上一節(jié)的,響應(yīng)式基本原理只適用當(dāng)前組件(實(shí)例)欠母,
當(dāng)其他子組件也依賴(lài)這些數(shù)據(jù)欢策,或者有多個(gè)地方用到這個(gè)數(shù)據(jù)的時(shí)候,數(shù)據(jù)更新赏淌,其他的地方能收到通知踩寇,那么依賴(lài)收集就能用到了。
看代碼
//一個(gè)屬性擁有一個(gè)自己的dep對(duì)象
class Dep {
constructor () {
this.subs = [];
}
addSub (sub) {
this.subs.push(sub);
}
notify () {
this.subs.forEach((sub) => {
sub.update();
})
}
}
class Watcher {
update () {
console.log("視圖更新啦~");
}
}
function observer (value) {
if (!value || (typeof value !== 'object')) {
return;
}
Object.keys(value).forEach((key) => {
defineReactive(value, key, value[key]);
});
}
let n=0
function defineReactive (obj, key, val) {
const dep = new Dep();
Object.defineProperty(obj, key, {
enumerable: true,
configurable: true,
get: function reactiveGetter () {
n++
console.log(n,key)
dep.addSub(new Watcher());//區(qū)別點(diǎn)
return val;
},
set: function reactiveSetter (newVal) {
if (newVal === val) return;
dep.notify();
}
});
//console.log(dep)
}
class Vue {
constructor(options) {
this._data = options.data;
observer( this._data);
console.log('render~', this._data);
}
}
let a = new Vue({
data: {
x:1,
y:2
}
});
let b = new Vue({
data: {
w: "I am test. b",
z:3
}
});
調(diào)用了四次get六水,當(dāng)值改變的時(shí)候俺孙,通知dep所有的wacher,即一個(gè)屬性為一個(gè)Dep實(shí)例
51001.png
下面是染陌老師的
class Dep {
constructor () {
this.subs = [];
}
addSub (sub) {
this.subs.push(sub);
}
notify () {
this.subs.forEach((sub) => {
sub.update();
})
}
}
class Watcher {
constructor () {
Dep.target = this;
}
update () {
console.log("視圖更新啦~");
}
}
function observer (value) {
if (!value || (typeof value !== 'object')) {
return;
}
Object.keys(value).forEach((key) => {
defineReactive(value, key, value[key]);
});
}
function defineReactive (obj, key, val) {
const dep = new Dep();
Object.defineProperty(obj, key, {
enumerable: true,
configurable: true,
get: function reactiveGetter () {
dep.addSub(Dep.target);//區(qū)別點(diǎn)
/*
一個(gè)vue實(shí)例一個(gè)wacther(),對(duì)應(yīng)著多個(gè)dep
*/
return val;
},
set: function reactiveSetter (newVal) {
if (newVal === val) return;
dep.notify();
}
});
}
class Vue {
constructor(options) {
this._data = options.data;
observer(this._data);
new Watcher();
console.log('render~', this._data.test);
}
}
let o = new Vue({
data: {
test: "I am test."
}
});
o._data.test = "hello,test.";
Dep.target = null;
在閉包中增加了一個(gè) Dep 類(lèi)的對(duì)象,用來(lái)收集 Watcher 對(duì)象掷贾。在對(duì)象被「讀」的時(shí)候睛榄,會(huì)觸發(fā) reactiveGetter 函數(shù)把當(dāng)前的 Watcher 對(duì)象(存放在 Dep.target 中)收集到 Dep 類(lèi)中去。之后如果當(dāng)該對(duì)象被「寫(xiě)」的時(shí)候想帅,則會(huì)觸發(fā) reactiveSetter 方法场靴,通知 Dep 類(lèi)調(diào)用 notify 來(lái)觸發(fā)所有 Watcher 對(duì)象的 update 方法更新對(duì)應(yīng)視圖。