js-EventBus

111 阅读1分钟
  class EventBus {
      constructor() {
          this._event = new Map()
      }
      // 订阅
      on (type, fn) {
          let handler = this._event.get(type)
          if(!handler) {
              this._event.set(type, [fn])
          } else {
              handler.push(fn)
          }
      }
      // 发布
      emit (type, ...args) {
          let handler = this._event.get(type)
          handler.forEach((fn) => {
              fn.apply(this, args)
          })
      }
      // 取消订阅
      off (type, fn) {
          let handler = this._event.get(type)
          // 查找取消订阅的方法的索引
          handler.splice(handler.findIndex(e => e === fn), 1) // handler.indexOf(fn)
      }
      // 只执行一次
      once (type, fn) {
          let _self = this
          function handler () {
              // 删除type下的handler函数
              _self.off(type, fn)
              fn.apply(null, arguments)
          }
          // type下添加handler函数
          this.on(type, handler)
      }
  }