A simple Promise-based event bus service.
npm install eventserviceimport EventService from "eventservice";
// Subscribe to an event named "SomeEventName"
EventService.on("SomeEventName", async () => {
console.log("Did something!");
});
// Trigger the event
await EventService.fire("SomeEventName");
// -> Did something!import EventService from "eventservice";
// Subscribe to an event named "SomeEventName"
EventService.on("SomeEventName", async (date: Date) => {
console.log(date);
});
// Trigger the event
await EventService.fire("SomeEventName", new Date());
// -> current dateimport EventService from "eventservice";
// Subscribe to an event named "SomeEventName"
EventService.on("SomeEventName", async () => {
return "Hello World!";
});
// Trigger the event
const result: string | undefined = await EventService.fire<string>("SomeEventName");
console.log(result); // -> Hello World!import EventService from "eventservice";
// Subscribe to an event named "SomeEventName2"
EventService.on("SomeEventName2", (name: string) => {
return new Promise<string>((resolve) => {
setTimeout(() => resolve(`Hello ${name}!`), 5000);
});
});
// Subscribe to an event named "SomeEventName1"
EventService.on("SomeEventName1", async (name: string) => {
return await EventService.fire<string>("SomeEventName2", name);
});
// Trigger the event
const result: string | undefined = await EventService.fire<string>("SomeEventName1", "World");
console.log(result); // after 5s -> Hello World!You can use the off method.
import EventService from "eventservice";
// Subscribe to an event named "SomeEventName"
EventService.on(
"SomeEventName",
async (name: string) => {
return `Hello ${name}!`;
},
"SomeKey",
);
// Unsubscribe from the event
EventService.off("SomeEventName", "SomeKey");
// Trigger the event
const result: string | undefined = await EventService.fire<string>("SomeEventName", "World");
console.log(result); // -> undefinedSubscribes to an event.
eventName— event namecallback— async callback that will be called when the event is firedkey— optional subscription key used for unsubscribing
Unsubscribes from an event by key.
Fires an event and waits until all subscribers finish.
Removes all subscriptions.
MIT