forked from janhq/jan
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patheventsService.ts
42 lines (33 loc) · 1000 Bytes
/
eventsService.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/* eslint-disable @typescript-eslint/ban-types */
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)
})
}
}