观察者模式
目标直接将通知分发到观察者身上
发布订阅者模式
目标首先将通知分发到事件调度中事件调度中心通过订阅者具体订阅的类型分发到不同的订阅者身上
class Observe{
constructor(){
this.cache = {};
};
on(name,fn) {
if(!this.cache[name]){
this.cache[name] =[]
}
this.cache[name].push(fn)
};
// 发布
emit( name ,msg) {
if(!this.cache[name]){
return;
}
this.cache[name].forEach(cb=>cb(msg));
};
// 移出
off(name,fn) {
if(this.cache[name]){
this.cache[name].fn = this.cache[name].fn.filter(item=> item != fn)
}
// if(!name){
// this.cache={}
// // 移除这个事件类型下的这个函数
// }else if(name && !fn){
// delete this.cache[name]
// }else{
// this.cache[name] = this.cache[name].filter((cb) =>{
// })
// }
};
}