All files / src/core EventBus.ts

100% Statements 47/47
100% Branches 13/13
100% Functions 7/7
100% Lines 47/47

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 481x 1x 1x 42x 1x 1x 21x 16x 16x 21x 21x 1x 1x 9x 9x 8x 8x 7x 7x 8x 9x 1x 1x 88x 88x 14x 15x 15x 15x 2x 2x 15x 14x 88x 1x 1x 5x 4x 4x 4x 5x 5x 1x 1x 3x 3x 1x  
type Handler = (...args: unknown[]) => void;
 
export class EventBus {
  private handlers: Map<string, Handler[]> = new Map();
 
  on(event: string, handler: Handler): void {
    if (!this.handlers.has(event)) {
      this.handlers.set(event, []);
    }
    this.handlers.get(event)!.push(handler);
  }
 
  off(event: string, handler: Handler): void {
    const eventHandlers = this.handlers.get(event);
    if (eventHandlers) {
      const index = eventHandlers.indexOf(handler);
      if (index > -1) {
        eventHandlers.splice(index, 1);
      }
    }
  }
 
  emit(event: string, ...args: unknown[]): void {
    const eventHandlers = this.handlers.get(event);
    if (eventHandlers) {
      for (const handler of eventHandlers) {
        try {
          handler(...args);
        } catch (e) {
          console.error('[LightSDK] EventBus handler error:', e);
        }
      }
    }
  }
 
  once(event: string, handler: Handler): void {
    const wrapped = (...args: unknown[]) => {
      this.off(event, wrapped);
      handler(...args);
    };
    this.on(event, wrapped);
  }
 
  destroy(): void {
    this.handlers.clear();
  }
}