栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

简易版事件总线实现

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

简易版事件总线实现

手写时间简易版事件总线

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

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

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

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

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

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

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

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

事件的监听方法on;

事件的发射方法emit;

事件的取消监听off;

class DYEventBus {
  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) {
    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)
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/666868.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号