手写 实现发布-订阅模式

99 阅读1分钟
class EvenCenter {
  constructor() {
    // 定义事件容器,用来装事件数组
    this.handlers = {}
  }

  // 添加事件方法,参数:事件名,事件方法
  addEventListener(type, handler) {
    // 创建新建数组容器
    if (!this.handlers[type]) {
      this.handler[type] = []
    }

    // 存入事件
    this.handlers[type].push(handler)
  }

  // 触发事件,参数:事件名,事件参数
  dispatchEvent(type, params) {
    // 若没有注册事件则抛出错误
    if (!this.handlers[type]) {
      throw new Error('This event is not registered')
    }
    // 触发事件
    this.handlers[type].forEach((handler) => {
      handler(...params)
    })
  }

  // 事件移除,参数:事件名,要删除事件
  removeEventListener(type, handler) {
    // 要删除的事件不存在
    if (!this.handlers[type]) {
      throw new Error('Invalid event')
    }
    if (!handler) {
      // 移除事件
      delete this.handlers[type]
    }
    // 没有第二个参数的情况
    else {
      // 无该绑定事件
      const index = this.handlers[type].findIndex((el) => el === handler)
      if (index === -1) {
        throw new Error('No such bound event')
      }
      // 删除整个事件
      this.handlers[type].splice(index, 1)
      // 若无第二个参数则删除该事件的订阅和发布
      if (this.handlers[type].length === 0) {
        delete this.handlers[type]
      }
    }
  }
}