发布订阅者模式主要有一个收集依赖的属性,及实现三个方法(为方便大家理解和记忆,使用Vue中的事件总线对应方法命名,自己手写时可以对照事件总线的使用去帮助提供思路)
1.依赖收集属性
依赖收集可以使用map,也可以使用普通对象,对象的每个key对应的值为一个数组,用于存放该key对应的依赖
2.事件监听方法(on)
该方法用于收集依赖,如果某个key对应的依赖从未被添加,则初始化一个数组用于保存该项依赖。如已被添加过,则直接往该数组push新依赖
3.事件销毁方法(off)
该方法用于销毁依赖,如果传入了对应的type,则仅将该type对应的依赖置空,如没传type,则将所有依赖置空
4.事件触发方法(emit)
该方法用于触发依赖,根据传入的type,找到该type对应的依赖并遍历,依次执行。
class Observer {
constructor() {
this.message = {}
}
on(type, fn) {
if (typeof fn !== 'function') {
throw new Error('fn must be a function')
}
if ( !this.message[type] ) {
this.message[type] = []
}
this.message[type].push(fn)
}
off(type) {
if (!type) {
this.message = {}
} else {
this.message[type] = []
}
}
emit(type, ...args) {
const target = this.message[type]
if (target) {
for( const depend of target ) {
depend(...args)
}
}
}
}