-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathBindingManager.js
78 lines (62 loc) · 1.85 KB
/
BindingManager.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import parseBindings, { MODE_HANDLE } from './parseBindings'
export default class BindingManager {
constructor (client, element) {
this.client = client
this.element = element
this._handlers = new Map()
this.update()
}
update () {
const targetBindings = this._parseBindings()
this._removeExtraHandlers(targetBindings)
this._setupMissingHandlers(targetBindings)
}
shutdown () {
for (const [eventName, callback] of this._handlers.values()) {
this.element.removeEventListener(eventName, callback)
}
this._handlers.clear()
}
_parseBindings () {
const { motionAttribute } = this.client
const bindingsString = this.element.getAttribute(motionAttribute)
const bindings = new Map()
for (const binding of parseBindings(bindingsString, this.element)) {
bindings.set(binding.id, binding)
}
return bindings
}
_buildHandlerForBinding ({ mode, motion }) {
return (event) => {
const component = this._getComponent()
if (
component &&
component.processMotion(motion, event, this.element) &&
mode === MODE_HANDLE
) {
event.preventDefault()
}
}
}
_getComponent () {
return this.client.getComponent(this.element)
}
_setupMissingHandlers (targetBindings) {
for (const [id, binding] of targetBindings.entries()) {
if (!this._handlers.has(id)) {
const { event } = binding
const handler = this._buildHandlerForBinding(binding)
this.element.addEventListener(event, handler)
this._handlers.set(id, [event, handler])
}
}
}
_removeExtraHandlers (targetBindings) {
for (const [id, [event, callback]] of this._handlers.entries()) {
if (!targetBindings.has(id)) {
this.element.removeEventListener(event, callback)
this._handlers.delete(id)
}
}
}
}