This library provides a simple and efficient way to manage events in your JavaScript or TypeScript applications. It allows you to create an event bus that you can subscribe to and publish events.
npm install native-pubsub
First, you need to create an event bus:
import { EventBus } from 'native-pubsub';
const eventBus = new EventBus();
// or create an event bus with a typed data structure:
const typedEventBus = new EventBus<{ id: string, name: string }>();
Event buses are unique, and it's recommended that you only publish (and subscribe to) one kind of events for each event bus.
To subscribe to an event, use the subscribe
method. This method takes a function that will be called when the event is triggered:
const unsubscribe = eventBus.subscribe((data) => {
console.log(data);
});
The subscribe
method returns a function that you can call to unsubscribe from the event.
To publish an event, you can use either the publish
or publishSync
method.
The publish
method publishes an event asynchronously:
eventBus.publish('Hello, world!');
The publishSync
method publishes an event synchronously:
eventBus.publishSync('Hello, world!');
Contributions are welcome! Please see the CONTRIBUTING.md
and CODE_OF_CONDUCT.md
files for more information.