@alister.codes/tsbus
v1.0.0
Published
Actually simple TS event bus with no dependencies ever
Downloads
2
Readme
TsBus
A minimal event bus for you to implement the pub/sub pattern with.
I have made it a class so you can create a new bus per use case.
- Zero dependencies
- Simple & easy to use
- Feature complete
How to use
Assuming we have the following...
const salesEventBus = new TsBus();
function handler(eventData) {
console.log("Received event: ", eventData);
}
.on
// Register the event
salesEventBus.on("MY_EVENT", handler);
You can register multiple handlers for a specific event. You can register a handler with multiple events.
.emit
// Emit the event (as many times as you want). `handler` is called each time the event is emitted.
salesEventBus.emit("MY_EVENT");
salesEventBus.emit("MY_EVENT");
As long as a handler is registered for an event, it will be called every time you emit the event.
.off
salesEventBus.off("MY_EVENT", handler);
// Handler will *not* be called again
salesEventBus.emit("MY_EVENT");
.once
Use EventBus.once
to call a handler only the first time the relevant event is emitted.
// Register the event
salesEventBus.once("MY_EVENT", handler);
salesEventBus.emit("MY_EVENT");
// Handler will *not* be called again
salesEventBus.emit("MY_EVENT");