-
Notifications
You must be signed in to change notification settings - Fork 49
/
bind.ts
90 lines (83 loc) · 2.64 KB
/
bind.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
80
81
82
83
84
85
86
87
88
89
90
const controllers = new Set<string>()
/*
* Bind `[data-action]` elements from the DOM to their actions.
*
*/
export function bind(controller: HTMLElement): void {
controllers.add(controller.tagName.toLowerCase())
bindElements(controller)
}
/**
* Set up observer that will make sure any actions that are dynamically
* injected into `el` will be bound to it's controller.
*
* This returns a Subscription object which you can call `unsubscribe()` on to
* stop further live updates.
*/
export function listenForBind(el: Node = document): Subscription {
let closed = false
const observer = new MutationObserver(mutations => {
for (const mutation of mutations) {
if (mutation.type === 'attributes' && mutation.target instanceof Element) {
bindActions(mutation.target)
} else if (mutation.type === 'childList' && mutation.addedNodes.length) {
for (const node of mutation.addedNodes) {
if (node instanceof Element) {
bindElements(node)
}
}
}
}
})
observer.observe(el, {childList: true, subtree: true, attributes: true, attributeFilter: ['data-action']})
return {
get closed() {
return closed
},
unsubscribe() {
closed = true
observer.disconnect()
}
}
}
interface Subscription {
closed: boolean
unsubscribe(): void
}
function bindElements(root: Element) {
for (const el of root.querySelectorAll('[data-action]')) {
bindActions(el)
}
// Also bind the controller to itself
if (root.hasAttribute('data-action')) {
bindActions(root)
}
}
// Bind a single function to all events to avoid anonymous closure performance penalty.
function handleEvent(event: Event) {
const el = event.currentTarget as Element
for (const binding of bindings(el)) {
if (event.type === binding.type && controllers.has(binding.tag)) {
const controller = el.closest(binding.tag) as Element & Record<string, (ev: Event) => unknown>
if (controller && typeof controller[binding.method] === 'function') {
controller[binding.method](event)
}
}
}
}
type Binding = {type: string; tag: string; method: string}
function* bindings(el: Element): Iterable<Binding> {
for (const action of (el.getAttribute('data-action') || '').split(' ')) {
const eventSep = action.lastIndexOf(':')
const methodSep = action.lastIndexOf('#')
const type = action.slice(0, eventSep)
const tag = action.slice(eventSep + 1, methodSep)
const method = action.slice(methodSep + 1)
yield {type, tag, method}
}
}
function bindActions(el: Element) {
for (const binding of bindings(el)) {
el.addEventListener(binding.type, handleEvent)
}
}