手写发布订阅者模式和eventBus

简单讲就是创建一个submit主题,然后submit维护一个订阅了这个主题的观察者数组,主体里有些方法可以操作观察者,比如添加观察者、删除观察者以及通知所有观察者更新主题。

class submit(){
    observers=[];
    addObservers(observer){
            this.observers.push(observer);
    }
     removeObervers(observer){
            let index=this.observers.indexOf(observer);
            observers.splice(index,1);
    }
    
    notify(){
          this.observers.forEach(item=>{item.update()})
    }
}


class observer{
      update(){};
      subscribeTo(subject){
            subject.addObservers(this);
      }
}

eventBus 写法:

class EventBus{
let bus={};
on(type,handler){
    this.bus[type]=(this.bus[type] || []).concat(handler);
}
fire(type,data){
    this.bus[type] || this.bus[type].forEach(i=>i(data));
}

off(type,handler){
    if(this.bus[type]){
          if(!handler){
            delete this.bus[type];
          }
          else{
              let index=this.bus[type].indexOf(handler);
              bus[type].splice(index,1);
          }
     }
}
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。