首页 > 其他分享 >JS手写题随笔-20221211.1 ---- 事件中心(发布订阅)

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

时间:2022-12-11 21:23:08浏览次数:55  
标签:Function 20221211.1 string JS ---- handler fn type store

发布订阅事件中心的实现

// 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);
    });
  }
}

 

标签:Function,20221211.1,string,JS,----,handler,fn,type,store
From: https://www.cnblogs.com/fanqshun/p/16974509.html

相关文章