Class: EventDispatchService
Event Dispatch Service
This service coordinates the dispatching of events to the NestJS EventEmitter module.
Constructors
new EventDispatchService()
new EventDispatchService(
eventEmitter):EventDispatchService
Constructor
Parameters
| Parameter | Type | Description |
|---|---|---|
eventEmitter | EventEmitter2 | Injected event emitter instance |
Returns
Defined in
Methods
async()
async<
E>(event):Promise<EventReturnPayload<E,EventReturnType<E>>[]>
Dispatch an event asynchronously.
Asynchronously calls each of the listeners registered for the event, in the order they were registered, passing the event arguments to each.
Type Parameters
| Type Parameter |
|---|
E |
Parameters
| Parameter | Type | Description |
|---|---|---|
event | E & EventAsyncInstance<E> | The event being dispatched. |
Returns
Promise<EventReturnPayload<E, EventReturnType<E>>[]>
An array of return payloads, one for each listener that subscribed to the event.
Example
import { Injectable } from '@nestjs/common';
import { EventDispatchService, EventAsync } from '@concepta/nestjs-events';
// expected object
export type MyPayloadType = {id: number, active: boolean};
// event class
export class MyEvent extends EventAsync<MyPayloadType> {}
@Injectable()
class MyClass {
constructor(private eventDispatchService: EventDispatchService) {}
// allow any listener to activate object
async maybeActivate(myPayloadType: MyPayloadType): MyPayloadType {
// event instance
const myEvent = new MyEvent({...myPayloadType, active: false});
// dispatch the event
const allPayloads: MyPayloadType[] =
await this.eventDispatchService.async(myEvent);
// merge it
allPayloads.forEach((payload) => {
// did any listener set it to true?
if (payload.active) {
myPayloadType.active = true;
}
});
// return possibly modified object
return myPayloadType;
}
}Defined in
sync()
sync<
P>(event):boolean
Dispatch an event synchronously.
Synchronously calls each of the listeners registered for the event, in the order they were registered, passing the event arguments to each.
Type Parameters
| Type Parameter |
|---|
P |
Parameters
| Parameter | Type | Description |
|---|---|---|
event | EventSyncInterface<P> | The event being dispatched. |
Returns
boolean
boolean Returns true if the event had listeners, false otherwise.
Example
import { Injectable } from '@nestjs/common';
import { EventDispatchService, EventSync } from '@concepta/nestjs-events';
// event payload type
export type MyPayloadType = {id: number};
// event class
export class MyEvent extends EventSync<MyPayloadType> {}
@Injectable()
class MyClass {
constructor(private eventDispatchService: EventDispatchService) {}
didSomething() {
// event instance
const myEvent = new MyEvent({id: 1234});
// dispatch the event
this.eventDispatchService.sync(myEvent);
}
}