@dkx/event-dispatcher
v0.0.1
Published
Event dispatcher for node.js
Downloads
2
Readme
DKX/EventDispatcher
Event dispatcher for node.js
Installation
Dependencies:
reflect-metadata
with npm:
$ npm install --save @dkx/event-dispatcher
or with yarn:
$ yarn add @dkx/event-dispatcher
Events
Events should be small value object classes implementing the Event
interface.
import {Event} from '@dkx/event-dispatcher';
class UserUpdatedEvent implements Event
{
constructor(
public readonly user: User,
public readonly changes: any,
) {}
}
Subscribers
Subscribers are classes which contains subscriptions to defined events. They should implement the Subscriber
interface.
import {Subscriber, Subscribe} from '@dkx/event-dispatcher';
import {UserUpdatedEvent} from './user-updated-event';
class UserUpdatedEmailNotification implements Subscriber
{
@Subscribe()
public onUserUpdated(event: UserUpdatedEvent): void
{
console.log(event);
// todo send email
}
}
Event to which the subscriber should subscribe is taken from method argument type (event: UserUpdatedEvent
).
Subscription method can be also async
and return Promise
.
Call event
import {EventDispatcher} from '@dkx/event-dispatcher';
import {UserUpdatedEvent} from './user-updated-event';
import {UserUpdatedEmailNotification} from './user-updated-email-notification';
// create and register first subscriber
const events = new EventDispatcher;
events.addSubscriber(new UserUpdatedEmailNotification);
// dispatch event
events.dispatch(new UserUpdatedEvent(user, {}));