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