createMediator()
createMediator<
Events>(): Mediator<Events>
Creates a typed mediator for decoupled component communication.
Components emit events without knowing who handles them. The mediator routes events to registered handlers, enabling loose coupling.
Type Parametersβ
Events: Events extends Record<string, unknown>β
Record mapping event names to payload types
Returns: Mediator<Events>β
A mediator with on, emit, and clear methods
Sinceβ
2.4.0
Exampleβ
type UIEvents = {
buttonClicked: { buttonId: string };
formSubmitted: { data: FormData };
modalClosed: { modalId: string };
};
const ui = createMediator`<UIEvents>`();
// Dialog component
ui.on("buttonClicked", ({ buttonId }) => {
if (buttonId === "confirm") ui.emit("modalClosed", { modalId: "dialog" });
});
// Form component
ui.on("formSubmitted", ({ data }) => {
validate(data);
ui.emit("buttonClicked", { buttonId: "confirm" });
});
Handler()<T>β
Handler<
T> = (payload) =>void
Event handler function type. Replaces the GoF Colleague callback interface.
Type Parametersβ
T: Tβ
The event payload type
Parametersβ
payload: Tβ
Returns: voidβ
Sinceβ
2.4.0
Mediator<Events>β
Mediator<
Events> =object
Mediator interface for typed event routing. Replaces the GoF Mediator abstract class.
Sinceβ
2.4.0
Type Parametersβ
Events: Events extends Record<string, unknown>β
Record mapping event names to payload types
Propertiesβ
on(): <K>(event, handler) => () => voidβ
Register a handler for an event type. Returns unsubscribe function.
Type Parametersβ
K: K extends keyof Eventsβ
event:
K
handler:Handler<Events[K]>
Returns:> (): void
Returns: voidβ
emit(): <K>(event, payload) => voidβ
Emit an event to all registered handlers.
Type Parametersβ
K: K extends keyof Eventsβ
event:
K
payload:Events[K]
Returns:void
clear(): (event?) => voidβ
Remove all handlers for an event type, or all handlers if no event specified.
event?:
keyof Events
Returns:void