fn
useEventBus
v0.0.14testeddemoA typed, SSR-safe event bus. Calls sharing an identifier share
listeners, giving cross-component (and cross-module) communication without
prop drilling or provide/inject. Backed by stdlib PubSub for stable
snapshot-based emit semantics, and auto-removes the current scope's
listeners on dispose so components never leak subscriptions.
Examples
ts
// shared key (typically exported from a module)
const busKey: EventBusKey<string> = Symbol('messages');
// component A
const bus = useEventBus(busKey);
const unsubscribe = bus.on((msg) => console.log(msg));
// component B
useEventBus(busKey).emit('hello');ts
// payloads and one-shot listeners
const bus = useEventBus<'open' | 'close', { id: number }>('modal');
bus.once((event, payload) => console.log(event, payload?.id));
bus.emit('open', { id: 1 });Demo
Loading demo…
Signature
ts
export function useEventBus<T = unknown, P = unknown>(
key: EventBusIdentifier<T>,
): UseEventBusReturn<T, P>{ ... }Type Parameters
T= unknownP= unknownParameters
| Parameter | Type | Description |
|---|---|---|
key | EventBusIdentifier<T> | Identifier shared across buses; equal keys share listeners |
Returns
UseEventBusReturn<T, P>The bus controls: on, once, off, emit, reset| Property | Type | Description |
|---|---|---|
on | (listener: EventBusListener<T, P>) => VoidFunction | Subscribe to the bus. Every emit invokes the listener. |
once | (listener: EventBusListener<T, P>) => VoidFunction | Subscribe to the bus for a single emit, then auto-unsubscribe. |
off | (listener: EventBusListener<T, P>) => void | Remove a previously registered listener. |
emit | (event?: T, payload?: P) => void | Emit an event to every listener on this bus. |
reset | () => void | Remove every listener on this bus. |