@alister.codes/tsbus
TypeScript icon, indicating that this package has built-in type declarations

1.0.0 • Public • Published

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");

Readme

Keywords

Package Sidebar

Install

npm i @alister.codes/tsbus

Weekly Downloads

1

Version

1.0.0

License

MIT

Unpacked Size

4.92 kB

Total Files

7

Last publish

Collaborators

  • alister.codes