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
-
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(); -
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`); }); -
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.queuedEventsorevents.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