简易版事件总线实现

手写时间简易版事件总线

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

发布者(Publisher):发出事件(Event);

订阅者(Subscriber):订阅事件(Event),并且会进行响应(Handler);

事件总线(EventBus):无论是发布者还是订阅者都是通过事件总线作为中台的;

当然我们可以选择一些第三方的库:

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

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

当然我们也可以实现自己的事件总线:

事件的监听方法on;

事件的发射方法emit;

事件的取消监听off;

class DYEventBus {
  constructor() {
    this.eventBus = {}
  }

  /**
   *
   * @param {*} eventName 事件名称
   * @param {*} eventCallback 函数
   * @param {*} thisArg 需要绑定的this
   */
  on(eventName, eventCallback, thisArg) {
    let handlers = this.eventBus[eventName]
    if (!handlers) {
      handlers = []
      this.eventBus[eventName] = handlers
    }
    handlers.push({
      eventCallback,
      thisArg
    })
  }

  off(eventName, eventCallback) {
    const 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) return
    handlers.forEach((handler) => {
      handler.eventCallback.apply(handler.thisArg, payload)
    })
  }
}

const eventBus = new DYEventBus()

// main.js
eventBus.on(
  'abc',
  function () {
    console.log('监听abc1', this, arguments)
  },
  { name: 'zdy' }
)

const handleCallback = function (...args) {
  console.log('监听abc2', this, args)
  //   console.log(args)
}
eventBus.on('abc', handleCallback, { name: 'why' })

// utils.js
eventBus.emit('abc', 123, 234, 456)

// 移除监听
eventBus.off('abc', handleCallback)
eventBus.emit('abc', 123)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值