To implement the event emitter class, I will create a TypeScript file called 'eventEmitter.ts' which will contain the implementation of the EventEmitter class. This class will have methods to subscribe, unsubscribe and emit events. Here is the code for 'eventEmitter.ts':
import { TypedEvent } from './typedEvent';
export class EventEmitter<T> {
private listeners: Map<string, Array<TypedEvent<T>>> = new Map();
public subscribe(eventName: string, listener: TypedEvent<T>): void {
if (!this.listeners.has(eventName)) {
this.listeners.set(eventName, []);
}
this.listeners.get(eventName)?.push(listener);
}
public unsubscribe(eventName: string, listener: TypedEvent<T>): void {
const eventListeners = this.listeners.get(eventName);
if (eventListeners) {
const index = eventListeners.indexOf(listener);
if (index !== -1) {
eventListeners.splice(index, 1);
}
}
}
public emit(eventName: string, payload: T): void {
const eventListeners = this.listeners.get(eventName);
if (eventListeners) {
eventListeners.forEach(listener => listener(payload));
}
}
}
I will create another TypeScript file called 'typedEvent.ts' which will declare the type for the event payload. Here is the code for 'typedEvent.ts':
export type TypedEvent<T> = (payload: T) => void;
To use the event emitter, you can import it in your main TypeScript file ('main.ts') and create an instance of EventEmitter. Then you can subscribe to events, unsubscribe and emit events as needed.
Commit Message: Added event emitter class and typed event payload support
To implement the event emitter class, I will create a TypeScript file called 'eventEmitter.ts' which will contain the implementation of the EventEmitter class. This class will have methods to subscribe, unsubscribe and emit events. Here is the code for 'eventEmitter.ts':
I will create another TypeScript file called 'typedEvent.ts' which will declare the type for the event payload. Here is the code for 'typedEvent.ts':
To use the event emitter, you can import it in your main TypeScript file ('main.ts') and create an instance of
EventEmitter
. Then you can subscribe to events, unsubscribe and emit events as needed.Commit Message: Added event emitter class and typed event payload support