/
event_handler.js
52 lines (41 loc) · 1.24 KB
/
event_handler.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
class EventHandler {
constructor (controller) {
this.eventHandlers = []
const controllerDisconnectCallback = controller.disconnect.bind(controller)
Object.assign(controller, {
handleEvent: this.handleEvent,
removeHandledEvents: this.removeHandledEvents,
disconnect () {
controllerDisconnectCallback()
this.removeHandledEvents()
}
})
}
handleEvent = (type, options = {}) => {
const element = options.on || document
const targetMatching = options.matching
const callback = options.with
const handler = {
listener (event) {
if (targetMatching) {
if (event.target.dataset.preventDelegation) { return }
const target = event.target.closest(targetMatching)
if (!target) { return }
}
callback(event)
},
removeListener () {
element.removeEventListener(type, this.listener)
}
}
element.addEventListener(type, handler.listener)
this.eventHandlers.push(handler)
}
removeHandledEvents = () => {
this.eventHandlers.forEach((handler) => handler.removeListener())
this.eventHandlers = []
}
}
export const installEventHandler = (controller) => {
return new EventHandler(controller)
}