自定义事件派发机制

简单实现事件的派发和监听

export default class EventEmitter {
  private events: any;

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

  /**
   * 监听 event 事件,触发时调用 callback 函数
   * @param event 
   * @param callback 
   * @returns 
   */
  on(event: string, callback: Function) {
    let callbacks = this.events[event] || [];
    callbacks.push(callback);
    this.events[event] = callbacks;
    return this;
  }

  /**
   * 停止监听 event 事件
   * @param event 
   * @param callback 
   * @returns 
   */
  off(event: string, callback: Function) {
    if (event === "*") {
      this.events = {};
      return this;
    }
    let callbacks = this.events[event];
    this.events[event] =
      callbacks && callbacks.filter((fn: Function) => fn !== callback);
    return this;
  }

  /**
   * 触发事件,并把参数传给事件的处理函数
   * @param event 
   * @param args 
   * @returns 
   */
  emit(event: string, ...args: any) {
    const callbacks = this.events[event];
    callbacks && callbacks.forEach((fn: Function) => fn.apply(null, args));
    return this;
  }
}

 

上一篇:关于Eclipse导入maven项目报空指针异常


下一篇:nginx 读取文件 进行用户认证 internal(限制内部调用)