@porkchopsandwich/event-autobus
v1.0.3
Published
A simple publish/subscribe event bus written in TypeScript.
Downloads
2
Maintainers
Readme
Event Autobus
A simple publish/subscribe event bus written in TypeScript.
Requires support (native or polyfill) for Map/Set.
Installation
npm install --save @porkchopsandwich/event-autobus
Use
JavaScript
import { eventAutobus } from "@porkchopsandwich/event-autobus";
// Create a bus
const bus = eventAutobus();
// Add a subscription, returns an object that can be used to unsubscribe later
const subscription = bus.subscribe("eventName", (payload) => {
// Act on payload
});
// Invoke listeners
bus.publish("eventName", {...payload});
// Unsubscribe later
subscription.unsubscribe();
TypeScript
Use TypeScript to get typings on event names and payloads.
import { eventAutobus, IEventAutobusTypeAndPayload } from "@porkchopsandwich/event-autobus";
// Define an interface describing the events and their payloads
interface IEvent1Payload {
value: string;
}
interface IBusTypeAndPayload extends IEventAutobusTypeAndPayload {
eventName1: IEvent1Payload;
}
// Create a bus
const bus = eventAutobus<IBusTypeAndPayload>();
// TypeScript automatically checks event names, AND types the payload
const subscription = bus.subscribe("eventName1", (payload) => {
// Act on payload
});
// Invoke listeners
bus.publish("eventName1", { value: "Hello" });
// Unsubscribe later
subscription.unsubscribe();