@pixotope/event-bus
v0.6.0
Published
Typed in-memory event bus for Pixotope Foundation
Readme
@pixotope/event-bus
Typed in-memory event bus for Pixotope Foundation.
Install
pnpm add @pixotope/event-busQuick start
import { EventBus } from "@pixotope/event-bus";
// Define the events this bus can carry and their payload types.
type Events = {
test: { payload: string };
test2: { payload: number };
};
const bus = new EventBus<Events>();
// Subscribe. `on` returns an unsubscribe function.
const off = bus.on("test", ({ payload }) => {
console.log("got test:", payload);
});
// Emit an event to all matching handlers.
bus.emit("test", { payload: "hello" });
// Unsubscribe either by calling the returned function...
off();
// ...or by calling `off` with the same type and handler reference.
const handler = ({ payload }: { payload: number }) => console.log(payload);
bus.on("test2", handler);
bus.off("test2", handler);
// Remove every handler on the bus.
bus.dispose();API overview
EventBus<Events>- typed, mitt-like, in-memory pub/sub event bus.on(type, handler)- subscribe to an event type (or"*"for every event); returns a function that unsubscribes.off(type, handler)- unsubscribe a specific handler from an event type.emit(type, event?)- emit an event, invoking every matching handler and any wildcard handlers.dispose()- remove all registered handlers.
See the generated API reference (pnpm typedoc) for full type signatures.
