EventEmitter的封装

本文共--字 阅读约--分钟 | 浏览: -- Last Updated: 2021-12-23

class EventEmitter {
  constructor() {
    this.handlers = {};
  }

  addListener(type, handler) {
    (this.handlers[type] || (this.handlers[type] = [])).push(handler);
  }

  /**
   *
   * @param {Object|String} e 事件对象 或者只传事件名称
   * @param {String} e.type 事件类型
   * @param {*} e.payload 事件相关信息
   */
  trigger(e) {
    const handleType = typeof e === "string" ? e : e.type;
    const handlers = this.handlers[handleType];
    if (Array.isArray(handlers)) {
      handlers.forEach((handler) => {
        handler(e);
      });
    }
  }

  /**
   *
   * @param {String} type 事件类型,不传默认清空所有事件
   * @param {Function} targetHandler 注册的事件,不传默认清空该类事件
   */
  removeListener(type, targetHandler) {
    if (!type) {
      this.handlers = {};
      return;
    }

    if (Array.isArray(this.handlers[type])) {
      if (targetHandler) {
        const handlers = this.handlers[type];
        handlers.forEach((handler, index) => {
          if (handler === targetHandler) {
            handlers.splice(index, 1);
          }
        });
      } else {
        this.handlers[type] = [];
      }
    }
  }
}

export default new EventEmitter();