JavaScript实现发布与订阅

1、代码

复制代码
class EventBus {
  constructor(){
    this.events = {};
  }
  on(event,handler){
   if(!this.events[event]){
     this.events[event] = [];
   }
    this.events[event].push(handler);
  }
  emit(event,data){
    if (this.events[event]){
      this.events[event].forEach((handler)=>{
        handler(data);
      })
    }
  }
  off(event,handler){
    if (this.events[event]) {
      this.events[event] = this.events[event].filter(h=>h !== handler)
    }
  }
  remove(event){
    delete this.events[event]
  }
}
export {
  EventBus
} 
复制
复制代码

2、使用方法

  

复制代码
const $bus = new EventBus();
//订阅
$bus.on("greet", func)

  //发布

 $bus.emit("greet", "word");

 //取消订阅

  $bus.off("greet",func);

 //删除订阅

  $bus.remove("greet");
 

 function func(arg){

  console.log(arg)

 }

复制
复制代码

 

  

posted on   久居我梦  阅读(17)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
历史上的今天:
2022-06-15 props双向绑定?v-bind.sync=''
2022-06-15 Vue的v-bind="$attrs"如何使用
点击右上角即可分享
微信分享提示