All files emitter.ts

100% Statements 18/18
100% Branches 6/6
100% Functions 7/7
100% Lines 18/18

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54            2x       31x       22x 18x     22x       8x 1x     7x   7x 7x         2x 1x   1x 2x           15x 9x     6x 8x        
export type EventName = "ready" | "refresh" | "update" | "activation";
 
export interface Listeners {
  [key: string]: Function[];
}
 
export class Emitter {
  private _listeners: Listeners;
 
  constructor() {
    this._listeners = {};
  }
 
  public addListener(eventName: EventName, fn: Function): void {
    if (typeof this._listeners[eventName] === "undefined") {
      this._listeners[eventName] = [];
    }
 
    this._listeners[eventName].push(fn);
  }
 
  public removeListener(eventName: EventName, fn: Function): void {
    if (typeof this._listeners[eventName] === "undefined") {
      return;
    }
 
    const index = this._listeners[eventName].indexOf(fn);
 
    if (index !== -1) {
      this._listeners[eventName].splice(index, 1);
    }
  }
 
  public removeAllListeners(eventName?: EventName): void {
    if (eventName) {
      this._listeners[eventName] = [];
    } else {
      Object.keys(this._listeners).forEach((key) => {
        this._listeners[key] = [];
      });
    }
  }
 
  public emit(eventName: EventName, ...args: any[]): void {
    if (typeof this._listeners[eventName] === "undefined") {
      return;
    }
 
    this._listeners[eventName].forEach((fn) => {
      fn(...args);
    });
  }
}