fn

useEventBus

v0.0.14testeddemo

A 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= unknown
P= unknown

Parameters

ParameterTypeDescription
keyEventBusIdentifier<T>Identifier shared across buses; equal keys share listeners

Returns

UseEventBusReturn<T, P>The bus controls: on, once, off, emit, reset
PropertyTypeDescription
on(listener: EventBusListener<T, P>) => VoidFunctionSubscribe to the bus. Every emit invokes the listener.
once(listener: EventBusListener<T, P>) => VoidFunctionSubscribe to the bus for a single emit, then auto-unsubscribe.
off(listener: EventBusListener<T, P>) => voidRemove a previously registered listener.
emit(event?: T, payload?: P) => voidEmit an event to every listener on this bus.
reset() => voidRemove every listener on this bus.