-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
59 lines (47 loc) · 1.24 KB
/
index.js
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
export class EventDelegate {
constructor(root) {
this.root = root;
this.handlers = [];
}
detach() {
this.handlers.forEach((h) => h.detach());
}
add(eventName, selector, callback, useCapture) {
const found = this.handlers.find(
(h) => h.selector === selector && h.eventName === eventName
);
if (found) {
return found.detach;
}
const handler = (e) => this.handleEvent(e, this.root, selector, callback);
this.root.addEventListener(eventName, handler, useCapture);
const detach = () =>
this.root.removeEventListener(eventName, handler, useCapture);
this.handlers.push({
eventName,
selector,
detach,
});
}
remove(eventName, selector) {
const found = this.handlers.find(
(h) => h.eventName === eventName && h.selector === selector
);
if (found) {
found.detach();
}
}
handleEvent(event, root, selector, callback) {
const elements = [];
let target = event.target;
while (target && target !== root) {
elements.push(target);
target = target.parentNode;
}
const match = elements.find((element) => element.matches(selector));
if (!match) {
return;
}
callback.call(match, event);
}
}