class Dep {
constructor () {
this.subs = [];
} addSub (sub: Watcher) {
this.subs.push(sub)
}
removeSub (sub: Watcher) {
remove(this.subs, sub)
}
/*Github:https://github.com/answershuto*/
notify () {
// stabilize the subscriber list first
const subs = this.subs.slice()
for (let i = 0, l = subs.length; i < l; i++) {
subs[i].update()
}
}
}
function remove (arr, item) {
if (arr.length) {
const index = arr.indexOf(item)
if (index > -1) {
return arr.splice(index, 1)
}
}
我们每次触发getter的时候,只要把触发的对象放到dep.sub里面就好啦!
但是现在问题来了,我们用什么来装这个触发的’对象’,也可以说式订阅者呢?
我们使用Watcher这个类
class Watcher {
constructor (vm, expOrFn, cb, options) {
this.cb = cb;
this.vm = vm; /*在这里将观察者本身赋值给全局的target,只有被target标记过的才会进行依赖收集*/
Dep.target = this;
/*Github:https://github.com/answershuto*/
/*触发渲染操作进行依赖收集*/
this.cb.call(this.vm);
}
update () {
this.cb.call(this.vm);
}
}
vm即是vue实例, expOrFn就是{{a+b}}里面的a+b, cb就是回调函数就是return a+b, options是一些配置项。
Vue在第一次渲染列表的时候如果碰到{{xxx}}这样的表达式,就会new Watcher()。解析里面的函数,然后把当前的watcher实例赋给Dep.target(Dep.target是全局的,一次性只能有一个存在,因为Vue一次只处理一个依赖)。然后执行回调函数。(这里看似是执行回调函数渲染,其实又触发了一次getter,然后就会把当前的依赖添加到sub里去)
接下来开始依赖收集
class Vue {
constructor(options) {
this._data = options.data;
observer(this._data, options.render);
let watcher = new Watcher(this, );
}
}function defineReactive (obj, key, val, cb) {
/*在闭包内存储一个Dep对象*/
const dep = new Dep();
Object.defineProperty(obj, key, {
enumerable: true,
configurable: true,
get: ()=>{
if (Dep.target) {
/*Watcher对象存在全局的Dep.target中*/
dep.addSub(Dep.target);
}
},
set:newVal=> {
/*只有之前addSub中的函数才会触发*/
dep.notify();
}
})
}
Dep.target = null; //防止依赖重复添加
这儿我们通过示例来讲解
<template>
<div>
{{a+b}}
</div>
<div>
{{a-c}}
</div>
</template>










