【vue】双向数据绑定(一)–发布订阅模式
一个最简单的发布订阅模式
- Dep 类
- 负责进行依赖收集
- 首先,有个数组,专门来存放所有的订阅信息
- 其次,还要提供一个向数组中追加订阅信息的方法
- 然后,还要提供一个循环,循环触发数组中的每个订阅信息
-
Watcher 类
负责订阅一些事件,将自己的一些行为交给了 Dep类,放在 Dep数组中。
当以后到了一定时机, Dep类负责对每一个行为进行循环,然后触发。此时 Watcher类就可以收到通知。
// 收集依赖/收集订阅者
class Dep {
constructor() {
// 这个 subs 数组,用来存放所有订阅者的信息
this.subs = []
}
// 向 subs 数组中,添加订阅者的信息
addSub(watcher) {
this.subs.push(watcher)
}
// 发布通知的方法
notify() {
this.subs.forEach((watcher) => watcher.update())
}
}
// 订阅者的类
class Watcher {
constructor(cb) {
this.cb = cb
}
// 触发回调的方法
update() {
this.cb()
}
}
//测试代码
const w1 = new Watcher(() => {
console.log('我是第1个订阅者')
})
const w2 = new Watcher(() => {
console.log('我是第2个订阅者')
})
const dep = new Dep()
dep.addSub(w1)
dep.addSub(w2)
dep.notify()
// 只要我们为 Vue 中 data 数据重新赋值了,这个赋值的动作,会被 Vue 监听到
// 然后 vue 要把数据的变化,通知到每个订阅者!!!
// 接下来,订阅者(DOM元素)要根据最新的数据,更新自己的内容