事件总线的简单实现

自定义事件总线

  • 自定义事件总线属于一种观察者模式,其中包括三个角色:
    • 发布者(Publisher):发出事件(Event);
    • 订阅者(Subscriber):订阅事件(Event),并且会进行响应(Handler);
    • 事件总线(EventBus):无论是发布者还是订阅者都是通过事件总线作为中台的;
class CWEventBus {
  constructor() {
    this.eventBus = {};
  }
	// 监听方法
  on(eventName, eventCallback, thisArg) {
    let handlers = this.eventBus[eventName];
    if (!handlers) {
      handlers = [];
      this.eventBus[eventName] = handlers;
    }
    handlers.push({
      eventCallback,
      thisArg,
    });
  }
	// 取消监听
  off(eventName, eventCallback) {
    let handles = this.eventBus[eventName];
    if (!handles) {
      return;
    }
    const newHandlers = [...handles];
    for (let index = 0; index < newHandlers.length; index++) {
      const handle = newHandlers[index];
      if (handle.eventCallback === eventCallback) {
        const handleIndex = handles.indexOf(handle);
        handles.splice(handleIndex, 1); // 删除
      }
    }
  }
 //发射方法
  emit(eventName, ...payload) {
    const handlers = this.eventBus[eventName];
    if (!handlers) {
      return;
    }
    handlers.forEach((item) => {
      // 触发函数并绑定this
      item.eventCallback.apply(item.thisArg, payload);
    });
  }
}

const eventbus = new CWEventBus();

function handleOn() {
  console.log("handleOn 监听", this);
}

// main.js

// 监听aaa
eventbus.on(
  "aaa",
  function () {
    console.log("监听aaa", this);
  },
  { name: "why" }
);

eventbus.on("aaa", handleOn, { name: "why2" });

// 在另一个文件里面触发aaa
eventbus.emit("aaa", 134);

// 取消aaa的第二个监听
eventbus.off("aaa", handleOn);
eventbus.emit("aaa", 123);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值