jan/web-app/src/services/events.ts
Louis 28c7e0d105
chore: stream app logs to log window (#5019)
* chore: stream app logs to log window

* chore: remove unused states
2025-05-19 22:51:37 +07:00

43 lines
1014 B
TypeScript

/* eslint-disable @typescript-eslint/no-unsafe-function-type */
export class EventEmitter {
private handlers: Map<string, Function[]>
constructor() {
this.handlers = new Map<string, Function[]>()
}
public on(eventName: string, handler: Function): void {
if (!this.handlers.has(eventName)) {
this.handlers.set(eventName, [])
}
this.handlers.get(eventName)?.push(handler)
}
public off(eventName: string, handler: Function): void {
if (!this.handlers.has(eventName)) {
return
}
const handlers = this.handlers.get(eventName)
const index = handlers?.indexOf(handler)
if (index !== undefined && index !== -1) {
handlers?.splice(index, 1)
}
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
public emit(eventName: string, args: any): void {
if (!this.handlers.has(eventName)) {
return
}
const handlers = this.handlers.get(eventName)
handlers?.forEach((handler) => {
handler(args)
})
}
}