-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtypedEventTarget.ts
44 lines (40 loc) · 1.43 KB
/
typedEventTarget.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
43
44
/**
* Map the keys to the CustomEvent details
*/
declare type EventDetails = {
[k: string]: any
}
/**
* EventTarget, but with types
*/
export class TypedEmitter<L extends EventDetails = EventDetails> {
private emitter = new EventTarget()
addEventListener<U extends keyof L>(
type: U,
listener: ((evt: CustomEvent<L[U]>) => void) | null,
options?: boolean | AddEventListenerOptions
) {
// the cast is necessary, since listener can only listen on Event (but it also works with customevents, typescript just doesn't like it)
return this.emitter.addEventListener(
type as string,
(listener as unknown) as EventListenerOrEventListenerObject | null,
options
)
}
/**
* dispatchEvent has been changed from the standard implementation, so it's easier to use and more stricly typeable
* @param event event name
* @param detail customevent data
* @returns boolean
*/
dispatchEvent<U extends keyof L>(event: U, detail?: L[U]): boolean {
return this.emitter.dispatchEvent(new CustomEvent(event as string, { detail }))
}
removeEventListener<U extends keyof L>(
type: U,
listener: ((evt: CustomEvent<L[U]>) => void) | null,
options?: boolean | AddEventListenerOptions
) {
return this.emitter.removeEventListener(type as string, (listener as unknown) as EventListener, options)
}
}