Event Bus Library
An ESM/CommonJS library following Oriented-Object Programming pattern to manager an Event Bus.
Features
- Publish, subscribe and unsubscribe to events;
- Change default event driver;
- Singleton & Oriented-Object Programming patterns;
- Better code organization.
This library was a requirement for some internal projects on our company. But it may work with another projects designed following Oriented-Object Programming pattern.
Installation
This library is ready for ES module or CommonJs module. You must add it by using Node.Js:
npm i --save @piggly/event-bus
Usage
First you must import EventBus
singleton. This is the main entry point for event bus management.
Registering Drivers
By default, EventBus
will start with LocalEventDriver
loaded and get/set dispatcher to it. But you can create your own event driver implementing EventDriverInterface
with your custom dispatcher extending EventDispatcher
.
By default, the publish()
, subscribe()
, unsubscrive()
and unsubscriveAll()
methods will you the LocalEventDriver
. But, you can change this behavior saying what driver must be loaded. E.g: publish(event, { driver: 'another' })
. The another
driver must be registered.
import EventBus from '@piggly/event-bus';
EventBus.instance.register(new AnotherEventDriver());
EventBus.instance.subscribe('EVENT_NAME', new SomeEventHandler());
EventBus.instance.subscribe('EVENT_NAME', new SomeEventHandler(), { driver: 'another' });
Operations
import EventBus from '@piggly/event-bus';
EventBus.instance.subscribe('EVENT_NAME', new SomeEventHandler());
EventBus.instance.unsubscrive('EVENT_NAME', new SomeEventHandler());
EventBus.instance.publish(new EventPayload('EVENT_NAME', {}));
Handlers & Payloads
You must create classes for handlers, it allows dispatcher avoid to add the same constructor classes into handler array of an event:
import { EventHandler, EventPayload } from '@piggly/event-bus';
export type StubEventData = {
value: number;
};
export class StubEventHandler extends EventHandler<StubEventData> {
public handle(event: EventPayload<StubEventData>): void {
console.log(event);
}
}
export class StubEventPayload extends EventPayload<StubEventData> {
constructor(data: { value: number }) {
super('STUB_EVENT', data);
}
}
export class StubEventHandler extends EventHandler<StubEventData> {
public handle(event: StubEventPayload): void {
console.log(event);
}
}
Changelog
See the CHANGELOG file for information about all code changes.
Testing the code
This library uses the Jest. We carry out tests of all the main features of this application.
npm run test:once
Contributions
See the CONTRIBUTING file for information before submitting your contribution.
Credits
License
MIT License (MIT). See LICENSE.