JS手写练习随笔-20221211.1 ---- 事件中心(发布订阅)

发布订阅事件中心的实现

// TS

class EventEmitter {
  // 事件中心
  private store: Record<string, Function[]>;

  constructor() {
    this.store = {};  
  }

  /**
   * 为某种类型的事件添加回调/处理函数
   */
  on(type: string, handler: Function) {
    // 如果已有该"type"的记录
    if (Array.isArray(this.store[type])) {
      this.store[type].push(handler);
    } 
    // 没有则初始化一个
    else {
      this.store[type] = [handler];
    }
  }

  /**
   * 清除某种类型的事件上特定的处理函数
   */
  off(type: string, handler: Function) {
    if (this.store[type] === undefined || this.store[type].length === 0) {
      return;
    }
    this.store[type] = this.store[type].filter((fn: Function) => {
      return fn !== handler;
    });
  }

  /**
   * 为某种类型的事件添加一次性的回调/处理函数
   */
  once(type: string, handler: Function) {
    const onceFn = () => {
      handler();
      this.off(type, onceFn);
    };
    this.on(type, onceFn);
  }

  /**
   * 触发相应类型的事件
   */
  emit(type: string, ...params: Parameters<any>) {
    if (this.store[type] === undefined || this.store[type].length === 0) {
      return;
    }
    this.store[type].forEach(fn => {
      fn.apply(this, params);
    });
  }
}

 

posted @ 2022-12-11 21:16  樊顺  阅读(32)  评论(0编辑  收藏  举报