-
Notifications
You must be signed in to change notification settings - Fork 0
/
listener.ts
84 lines (81 loc) · 1.8 KB
/
listener.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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
/**
* Listen to an event on an obj
*
* ex:
* const unlisten = listen(window, "resize", () => {})
*
* unlisten()
*
* @param obj
* @param event
* @param callback
* @param options
*/
export function listen<
K extends keyof (HTMLElementEventMap | DocumentEventMap | WindowEventMap),
>(
obj: HTMLElement | Window | Document,
event: (K | string) | (K | string)[],
callback: (
event: (HTMLElementEventMap | DocumentEventMap | WindowEventMap)[K],
) => any,
options?: boolean | AddEventListenerOptions,
): () => void {
if (typeof event === "string") event = [event]
for (let name of event) obj?.addEventListener(name, callback, options)
return () => {
for (let name of event) obj?.removeEventListener(name, callback, options)
}
}
/**
* Listen to an event on an obj, and remove the listener after the first call
*
* ex:
*
* listenOnce(window, "resize", () => {})
*
* @param obj
* @param event
* @param callback
* @param options
*/
export function listenOnce<
K extends keyof (HTMLElementEventMap | DocumentEventMap | WindowEventMap),
>(
obj: HTMLElement | Window | Document,
event: (K | string) | (K | string)[],
callback: (
event: (HTMLElementEventMap | DocumentEventMap | WindowEventMap)[K],
) => any,
options?: boolean | AddEventListenerOptions,
): () => void {
const unlisten = listen(
obj,
event,
(event) => {
unlisten()
callback(event)
},
options,
)
return unlisten
}
/**
* Compose listeners
*
* ex:
*
* const unlisten = listenCompose(
* listen(window, "resize", () => {})
* listen(window, "scroll", () => {})
* )
*
* unlisten()
*
* @param listeners
*/
export function listenCompose(...listeners: (() => void)[]): () => void {
return () => {
for (let listener of listeners) listener()
}
}