To implement the event emitter class in TypeScript, I will create a new file named eventEmitter.ts. This file will contain the code for the event emitter class. Here is the implementation:
// eventEmitter.ts
type EventHandler<T> = (payload: T) => void;
class EventEmitter<T> {
private events: Record<string, EventHandler<T>[]> = {};
public subscribe(eventName: string, handler: EventHandler<T>): void {
if (!this.events[eventName]) {
this.events[eventName] = [];
}
this.events[eventName].push(handler);
}
public unsubscribe(eventName: string, handler: EventHandler<T>): void {
const eventHandlers = this.events[eventName];
if (eventHandlers) {
this.events[eventName] = eventHandlers.filter((h) => h !== handler);
}
}
public emit(eventName: string, payload: T): void {
const eventHandlers = this.events[eventName];
if (eventHandlers) {
eventHandlers.forEach((handler) => handler(payload));
}
}
}
export default EventEmitter;
The EventEmitter class is a generic class that takes a type parameter T which represents the payload type of the events. It has three public methods:
subscribe(eventName: string, handler: EventHandler<T>): void: Adds a new event handler function to the specified event name.
unsubscribe(eventName: string, handler: EventHandler<T>): void: Removes an event handler function from the specified event name.
emit(eventName: string, payload: T): void: Emits an event with the specified name and payload, invoking all the event handler functions registered for that event name.
To use this event emitter in the NestJS application, I will update the existing app.module.ts file. Here is the updated code:
// app.module.ts
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import EventEmitter from './eventEmitter';
@Module({
imports: [],
controllers: [AppController],
providers: [AppService, EventEmitter],
})
export class AppModule {}
Solution
To implement the event emitter class in TypeScript, I will create a new file named
eventEmitter.ts
. This file will contain the code for the event emitter class. Here is the implementation:The
EventEmitter
class is a generic class that takes a type parameterT
which represents the payload type of the events. It has three public methods:subscribe(eventName: string, handler: EventHandler<T>): void
: Adds a new event handler function to the specified event name.unsubscribe(eventName: string, handler: EventHandler<T>): void
: Removes an event handler function from the specified event name.emit(eventName: string, payload: T): void
: Emits an event with the specified name and payload, invoking all the event handler functions registered for that event name.To use this event emitter in the NestJS application, I will update the existing
app.module.ts
file. Here is the updated code: