๐Ÿ“ฌ Event bus

Components emit and listen to named events without knowing about each other. Events nobody listens to yet wait in a queue.

Event bus with a queue

Components talk without importing each other: one emits a named event, others listen to it. If an event is emitted while nobody listens yet (for example a component that loads later), it waits in a queue instead of being lost.

๐Ÿ‘‰ Add a few products while the listener is offline: they pile up in the queue. Press Connect listener and they are delivered in order. Disconnect and try again.

Emitter

Queue 0

    Listener offline

    How to use it

    1. Create one bus and share it. Either export it from a module, or use the one every dispatcher already has: dispatcher.events.

      // shared.ts
      import { EventBus } from 'html-scoped-component-importer';
      
      export const events = new EventBus();
    2. Emit from any component with an event name and a payload.

      // components/ProductList.ts
      button.addEventListener('click', () => {
        events.emit('notify', `${product.name} added to the cart`);
      });
    3. Listen in another component. on() returns an unsubscribe function: call it in _destroy() so a removed component stops listening.

      // components/NotificationCenter.ts
      export default class NotificationCenter {
        private readonly unsubscribe: () => void;
      
        constructor(element: HTMLElement) {
          this.unsubscribe = events.on<string>('notify', message => showToast(message));
        }
      
        _destroy() {
          this.unsubscribe();
        }
      }

    Queue rules

    • โณ An event is queued only when its name has no listener; otherwise it is delivered immediately.
    • ๐Ÿฅ‡ Queued events go to the first listener that subscribes to that name, in emit order, then leave the queue.
    • ๐Ÿงบ At most 50 events per name are kept (oldest dropped first): new EventBus({ maximumQueuedPerEvent: 20 }).
    • ๐Ÿ”ญ Inspect it with events.queuedEvents or events.onQueueChange(queued => โ€ฆ), which is how the queue above is drawn.

    One event, many listeners

    Every listener of a name receives each event. These three swatches are independent components listening to theme:accent.

    // main.ts
    events.emit('theme:accent', '#ff5fa2');
    
    // components/Swatch.ts
    this.unsubscribe = events.on<string>('theme:accent', colour => {
      element.style.background = colour;
    });

    Queue limit

    This bus keeps at most 3 queued events per name. Keep clicking: the oldest one is dropped and the log shows a warning.

      const smallBus = new EventBus({ maximumQueuedPerEvent: 3 });
      smallBus.emit('tick', 1); // โ€ฆ the 4th tick drops tick 1