fn
useEventBus
v0.0.15testeddemoA 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 = any>(
key: EventBusIdentifier<T>,
): UseEventBusReturn<T, P>{ ... }Type Parameters
T= unknownP= anyParameters
| 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`