-
Notifications
You must be signed in to change notification settings - Fork 3
/
mod.ts
46 lines (44 loc) · 1.37 KB
/
mod.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
export function radEventListener<
MyElement extends { addEventListener: any; removeEventListener: any },
// get the possible events by using the `MyElement.on${someEvent}` properties
Event extends {
[K in keyof MyElement]-?: K extends `on${infer E}` ? E : never;
}[keyof MyElement]
>(
element: MyElement,
// recreate the args for addEventListener
...args: [
type: Event,
// grab the correct types off the function
listener: MyElement extends Record<
`on${Event}`,
null | ((...args: infer Args) => infer Return)
>
? // overwrite the type of this to make sure that it is always `MyElement`
(this: MyElement, ...args: Args) => Return
: never,
options?: boolean | AddEventListenerOptions
]
): () => void {
element.addEventListener(...args);
return () => {
element.removeEventListener(...args);
};
}
export { radEventListener as on };
export function rad<
MyElement extends { addEventListener?: any; removeEventListener?: any }
>(
element: MyElement,
gen: (rad: MyElement["addEventListener"]) => void
): () => void {
let cleanup: undefined | (() => void);
gen((listener: any, options: any) => {
element.addEventListener(listener, options);
cleanup = () => element.removeEventListener(listener, options);
});
if (!cleanup) {
throw new Error("you forgot to add event listener");
}
return cleanup;
}