-
-
Notifications
You must be signed in to change notification settings - Fork 382
/
event-hub.ts
79 lines (60 loc) · 1.74 KB
/
event-hub.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
import { Scrollbar } from '../interfaces/';
export interface EventHandler {
(event: any): void;
}
type EventConfig = {
elem: EventTarget,
eventName: string,
handler: EventHandler,
};
let eventListenerOptions: boolean | EventListenerOptions;
const eventMap = new WeakMap<Scrollbar, EventConfig[]>();
function getOptions(): typeof eventListenerOptions {
if (eventListenerOptions !== undefined) {
return eventListenerOptions;
}
let supportPassiveEvent = false;
try {
const noop = () => {};
const options = Object.defineProperty({}, 'passive', {
get() {
supportPassiveEvent = true;
},
});
window.addEventListener('testPassive', noop, options);
window.removeEventListener('testPassive', noop, options);
} catch (e) {}
eventListenerOptions = supportPassiveEvent ? { passive: false } as EventListenerOptions : false;
return eventListenerOptions;
}
export function eventScope(scrollbar: Scrollbar) {
const configs = eventMap.get(scrollbar) || [];
eventMap.set(scrollbar, configs);
return function addEvent(
elem: EventTarget,
events: string,
fn: EventHandler,
) {
function handler(event: any) {
// ignore default prevented events
if (event.defaultPrevented) {
return;
}
fn(event);
}
events.split(/\s+/g).forEach((eventName) => {
configs.push({ elem, eventName, handler });
elem.addEventListener(eventName, handler, getOptions());
});
};
}
export function clearEventsOn(scrollbar: Scrollbar) {
const configs = eventMap.get(scrollbar);
if (!configs) {
return;
}
configs.forEach(({ elem, eventName, handler }) => {
elem.removeEventListener(eventName, handler, getOptions());
});
eventMap.delete(scrollbar);
}