-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEventEmitter.ts
More file actions
62 lines (43 loc) · 1.6 KB
/
EventEmitter.ts
File metadata and controls
62 lines (43 loc) · 1.6 KB
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
type CustomEventConstructor<T> = new (...args: any) => T;
// https://stackoverflow.com/questions/51567462/typescript-class-extends-a-generic-type
type ExtractGeneric<T> = T extends CustomEvent<infer X> ? X : never;
type EventArgument<T> = ExtractGeneric<T>;
export class EventEmitter extends EventTarget {
private listeners: Record<string, Array<EventListenerOrEventListenerObject>> = {}
public emit<T extends CustomEvent>(event: T) {
this.dispatchEvent(event);
}
public on<T = typeof CustomEvent>(
event: CustomEventConstructor<T>,
callback: (e: EventArgument<T>) => void
) {
this.#on(event, callback);
}
public once<T = typeof CustomEvent>(
event: CustomEventConstructor<T>,
callback: (e: EventArgument<T>) => void,
) {
this.#on(event, callback, true);
}
public removeAllListeners() {
for (const eventType in this.listeners) {
const listeners = this.listeners[eventType];
listeners.forEach(l => {
this.removeEventListener(eventType, l as EventListenerOrEventListenerObject)
})
}
}
#on<T = typeof CustomEvent>(
event: CustomEventConstructor<T>,
callback: (e: EventArgument<T>) => void,
once: boolean = false
) {
const cb = (e: Event) => {
callback((e as CustomEvent).detail);
}
if (!this.listeners[event.name])
this.listeners[event.name] = [];
this.listeners[event.name].push(cb);
this.addEventListener(event.name, cb, { once });
}
}