-
Notifications
You must be signed in to change notification settings - Fork 67
Expand file tree
/
Copy pathaddEventListener.ts
More file actions
67 lines (59 loc) · 1.75 KB
/
addEventListener.ts
File metadata and controls
67 lines (59 loc) · 1.75 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
63
64
65
66
67
/* eslint-disable no-return-assign */
import canUseDOM from './canUseDOM.ts';
export let optionsSupported = false;
export let onceSupported = false;
try {
const options = {
get passive() {
return (optionsSupported = true);
},
get once() {
// eslint-disable-next-line no-multi-assign
return (onceSupported = optionsSupported = true);
},
};
if (canUseDOM) {
window.addEventListener('test', options as any, options);
window.removeEventListener('test', options as any, true);
}
} catch (e) {
/* */
}
export type EventHandler<K extends keyof HTMLElementEventMap> = (
this: HTMLElement,
event: HTMLElementEventMap[K]
) => any;
export type TaggedEventHandler<K extends keyof HTMLElementEventMap> = EventHandler<K> & {
__once?: EventHandler<K>;
};
/**
* An `addEventListener` ponyfill, supports the `once` option
*
* @param node the element
* @param eventName the event name
* @param handle the handler
* @param options event options
*/
function addEventListener<K extends keyof HTMLElementEventMap>(
node: HTMLElement,
eventName: K,
handler: TaggedEventHandler<K>,
options?: boolean | AddEventListenerOptions
) {
if (options && typeof options !== 'boolean' && !onceSupported) {
const { once, capture } = options;
let wrappedHandler = handler;
if (!onceSupported && once) {
wrappedHandler =
handler.__once ||
function onceHandler(event) {
this.removeEventListener(eventName, onceHandler, capture);
handler.call(this, event);
};
handler.__once = wrappedHandler;
}
node.addEventListener(eventName, wrappedHandler, optionsSupported ? options : capture);
}
node.addEventListener(eventName, handler, options);
}
export default addEventListener;