自定义事件总线

1.自定义事件总线

  • 自定义事件总线属于一种观察者模式,其中包括三个角色:

    • 发布者(Publisher):发出事件(Event)
    • 订阅者(Subscriber):订阅事件(Event)、并且会进行响应(Handler)
    • 事件总线(EventBus):无论是发布者还是订阅者都是通过事件总线作为中台的。
  • 当然我们可以选择一些第三方的库

    • Vue2默认是带有事件总线的功能

    • Vue3中推荐一些第三方库,比如mitt

  • 当然我们也可以实现自己的事件总线
    • 事件的监听方法on
    • 事件的发射方法emit
    • 事件的取消监听off
class JYEventBus{
  constructor(){
    this.eventBus={}
  }

  // * 监听,可以监听对次
  on(eventName,eventCallback,thisArg){
    let handlers=this.eventBus[eventName];
    if(!handlers){
      handlers=[];
      this.eventBus[eventName]=handlers;
    }
    handlers.push({
      thisArg,
      eventCallback
    });
  }

  off(eventName,eventCallback){
    let handlers=this.eventBus[eventName];
    if(!handlers) return;
    const newHandlers=[...handlers];
    for(let i=0;i<newHandlers.length;i++){
      const handler=newHandlers[i];
      if(handler.eventCallback==eventCallback){
        const index=handlers.indexOf(handler);
        handlers.splice(index,1)
      }
    }
  }

  emit(eventName,...payload){
    const handlers=this.eventBus[eventName];
     if(handlers){
       handlers.forEach(handler=>{
        handler.eventCallback.apply(handler.thisArg,payload);
       })
     }
  }
}

const eventBus=new JYEventBus();

// main.js
eventBus.on("abc",function(v){
 console.log("监听1vvv",v,this);
},{name:"why"})

// main.js
const handleCallback=function(v){
  console.log("监听2vvv",v,this);
 }
eventBus.on("abc",handleCallback,{name:"why"})
// utils.js
eventBus.emit("abc",123);

eventBus.off("abc",handleCallback)

eventBus.emit("abc","哈哈哈哈");
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容