===============================================================
-
需要用到数据的地方,称为依赖
-
Vue1.x,细粒度依赖,用到数据的DOM都是依赖
-
Vue2.x,中等粒度依赖,用到数组的组件是依赖
-
在getter中收集依赖,在setter中触发依赖
-
把依赖收集的代码封装成一个Dep 类,它专门用来管理依赖,每个Observer 的实例,成员中都有一个Dep 的实例;
-
Watcher 是一个中介,数据发生变化时通过Watcher 中转,通知组件
- 依赖就是Watcher 。只有Watch触发的getter才会收集依赖,哪个
Watcher 触发了getter,就把哪个Watch收集到Dep中。
- Dep 使用发布订阅模式,当数据发生变化时,会循环依赖列表,把所
有的Watcher 都通知一遍。
- 代码实现的巧妙之处:Watcher把自己设置到全局的一个指定位置,然后读取数据,因为读取了数据,所以会触发这个数据的getter。在getter 中就能得到当前正在读取数据的Watcher,并把这个Watcher 收集到Dep 中。
===============================================================
import observe from “./observe”;
import Watcher from “./Watcher”;
let obj = {
a: {
m: {
n: 5
}
},
b: 5,
c: {
d: {
e: {
f: 666
}
}
},
g: [22, 33, 44, 55]
};
observe(obj);
new Watcher(obj, ‘a.m.n’, (val) => {
console.log(‘☆☆☆☆☆’, val);
})
obj.a.m.n = 1;
console.log(obj);
import {def} from ‘./utils’
import defineReactive from “./defineReactive”;
import {arrayMethods} from ‘./array’
import observe from “./observe”;
import Dep from “./Dep”;
export default class Observer {
constructor(value) {
// 每一个observer的实例身上,都有一个dep
this.dep = new Dep();
// 给实例(this,一定要注意,构造函数中的this不是表示类本身,而是表示实例)
// 给实例添加了一个__ob__属性,值是这次new的实例
def(value, ‘ob’, this, false);
// console.log(‘我是Observer构造器’, value);
// 不要忘记初心,Observer类的目的是:将一个正常的object转换为每个层级的属性都是响应式(可被侦测)的object
// 检查是数组还是对象
if (Array.isArray(value)) {
// 如果是数组,要非常强行的蛮干:将这个数组的原型,指向arrayMethods
Object.setPrototypeOf(value, arrayMethods);
// 让这个数组变得observe
this.observeArray(value);
} else {
this.walk(value);
}
}
// 遍历
walk(value) {
for (let v in value) {
defineReactive(value, v);
}
}
// 数组的特殊遍历
observeArray(arr) {
for (let i = 0, l = arr.length; i < l; i++) {
// 逐项进行observe
observe(arr[i]);
}
}
}
import Observer from “./Observer”;
// 创建observe函数,注意函数的名字没有r
export default function observe(value) {
// 如果value不是对象,什么都不做
if (typeof value !== ‘object’) return;
// 定义ob
let ob;
ob = typeof value.ob !== ‘undefined’ ? value.ob : new Observer(value);
return ob;
}
import observe from “./observe”;
import Dep from “./Dep”;
export default function defineReactive(data, key, val) {
const dep = new Dep();
// console.log(‘我是defineReactive’, data, key)
if (arguments.length === 2) val = data[key];
// 子元素要进行observe,至此形成了递归。
// 这个递归不是函数调用自己,而是多个函数、类循环调用
let childOb = observe(val);
Object.defineProperty(data, key, {
// 可枚举
enumerable: true,
// 可以被配置,比如可以被外部delete
configurable: true,
get() {
console.log(你试图访问${key}属性
);
// 如果现在处于依赖收集节点
if (Dep.target) {
dep.depend();
if (childOb) {
childOb.dep.depend();
}
}
return val;
},
set(newValue) {
console.log(你试图改变${key}属性
, newValue);
if (val === newValue) return;
val = newValue;
// 当设置了新值,这个新值也需要被observe
childOb = observe(newValue);
// 发布订阅模式,通知dep
dep.notify();
}
})
}
export const def = function (obj, key, value, enumerable) {
Object.defineProperty(obj, key, {
value,
enumerable,
writable: true,
configurable: true
})
};
import {def} from “./utils”;
// 得到Array.prototype
const arrayPrototype = Array.prototype;
// 以arrayPrototype为原型创建arrayMethods对象 并 暴露
export const arrayMethods = Object.create(arrayPrototype);
const methodsNeedChange = [
‘push’,
‘pop’,
‘shift’,
‘unshift’,
‘splice’,
‘sort’,
‘reverse’
]
methodsNeedChange.forEach(methodName => {
// 备份原来的方法,因为push、pop等7个函数的功能不能被剥夺
const original = arrayPrototype[methodName];
// 定义新的方法
def(arrayMethods, methodName, function () {
// 恢复原来的功能
const result = original.apply(this, arguments);
// 把类数组对象变为数组
const args = […arguments];
// 把这个数组身上的__ob__取出来,__ob__已经被添加了,为什么已经被添加了?
// 因为数组肯定不是最高层,比如obj.g属性是数组,obj不能是数组,第一次遍历obj这个对象的第一层的时候已经给g属性(就是这个数组)添加了__ob__属性
const ob = this.ob;
// 有三种方法push/unshift/splice能够插入新项,现在要把插入的新项也变成observe的
let inserted = [];
switch (methodName) {
case ‘push’:
case ‘unshift’:
inserted = args;
break;
case ‘splice’:
// splice格式是splice(下标,数量,插入的新项)
inserted = args.slice(2);
break;
}
// 判断有没有要插入的新项,让新项也变成响应的
if (inserted) ob.observeArray(inserted);
console.log(‘啦啦啦’);
ob.dep.notify();
return result;
}, false)
})
let uid = 0;
export default class Dep {
constructor() {
this.id = uid++;
console.log(‘我是Dep的构造器’)
// 用数组存储自己的订阅者。subs是英语subscribes订阅者的意思
// 这个数组里面放的Watch的实例
this.subs = [];
}
// 添加订阅
addSub(sub) {
this.subs.push(sub);
}
// 添加依赖
depend() {
// Dep.target就是我们自己指定的一个全局位置,用window.target也行,只要是全局唯一,没有歧义就可以
if (Dep.target) this.addSub(Dep.target);
}
// 通知更新
notify() {
console.log(‘我是notify’)
// 浅克隆一份
const subs = this.subs.slice();
// 遍历
for (let i = 0; i < subs.length; i++) {
subs[i].update();
}
}
};
import Dep from “./Dep”;
let uid = 0;
export default class Watcher {
constructor(target, expression, callback) {
console.log(‘我是Watcher的构造器’)
this.id = uid++;
this.target = target;
this.getter = parsePath(expression);
this.callback = callback;
this.value = this.get();
}
update() {
this.run();
}
get() {
// 进入依赖收集阶段。让全局的Dep.target设置为Watcher本身,那么就是进入依赖收集阶段
Dep.target = this;
const obj = this.target;
let value;
// 只要能找,就一直找
try {
value = this.getter(obj);
} finally {
Dep.target = null;
}
return value;
}
run() {
this.getAndInvoke(this.callback);
}
getAndInvoke(cb) {
const value = this.get();
if (value !== this.value || typeof value == ‘object’) {
const oldValue = this.value;
this.value = value;
cb.call(this.target, value, oldValue);
}
}
};
function parsePath(str) {
let segments = str.split(‘.’);
return (obj) => {