事件总线

定义

  1. 属于一种观察者模式,其中包括三个角色:
    (1) 发布者 : 发出事件
    (2) 订阅者 : 订阅事件,并且会进行响应
    (3) 事件总线 : 无论是发布者还是订阅者都是通过事件总线作为中台的

  2. 代码

    class NanoEventBus {
      constructor() {
        this.eventBus = {}
      }
      on(eventName, eventCallback, thisArg) {
        let handler = this.eventBus[eventName]
        if (!handler) {
          handler = []
          this.eventBus[eventName] = handler
        }
        handler.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, ...playload) {
        const handler = this.eventBus[eventName]
        if (!handler) return
        handler.forEach(item => {
          if (item.thisArg) {
            item.eventCallback.apply(item.thisArg, playload)
          } else {
            item.eventCallback(...playload)
          }
        })
      }
    }

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!