All files / src/services eventBus.ts

100% Statements 13/13
100% Branches 6/6
100% Functions 5/5
100% Lines 9/9

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                    69x     8x 6x   8x       4x 4x       9x 8x       61x  
// src/services/eventBus.ts
 
/**
 * A simple, generic event bus for cross-component communication without direct coupling.
 * This is particularly useful for broadcasting application-wide events, such as session expiry.
 */
 
type EventCallback = (data?: unknown) => void;
 
export class EventBus {
  private listeners: { [key: string]: EventCallback[] } = {};
 
  on(event: string, callback: EventCallback): void {
    if (!this.listeners[event]) {
      this.listeners[event] = [];
    }
    this.listeners[event].push(callback);
  }
 
  off(event: string, callback: EventCallback): void {
    if (!this.listeners[event]) return;
    this.listeners[event] = this.listeners[event].filter((l) => l !== callback);
  }
 
  dispatch(event: string, data?: unknown): void {
    if (!this.listeners[event]) return;
    this.listeners[event].forEach((callback) => callback(data));
  }
}
 
export const eventBus = new EventBus();