Skip to content

Commit 819ca9c

Browse files
author
Philip Roberts
committed
Extract bindActionsToController method
1 parent b53ebdb commit 819ca9c

1 file changed

Lines changed: 25 additions & 18 deletions

File tree

catalyst/src/bind.ts

Lines changed: 25 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -4,31 +4,38 @@
44
*/
55
export function bind(controller: HTMLElement) {
66
const tag = controller.tagName.toLowerCase()
7-
for (const el of controller.querySelectorAll(`[data-action*=":${tag}#"]`)) {
7+
const actionAttributeMatcher = `[data-action*=":${tag}#"]`
8+
9+
for (const el of controller.querySelectorAll(actionAttributeMatcher)) {
810
// Ignore nested elements
911
if (el.closest(tag) !== controller) continue
12+
bindActionsToController(controller, el)
13+
}
14+
15+
// Bind the data-action attribute of a single element to the controller
16+
function bindActionsToController(controller: HTMLElement, el: Element) {
17+
const tag = controller.tagName.toLowerCase()
1018

11-
// Match the pattern of `eventName:constructor#method`.
12-
for (const binding of (el.getAttribute('data-action') || '').split(' ')) {
13-
const [rest, method] = binding.split('#')
19+
// Match the pattern of `eventName:constructor#method`.
20+
for (const binding of (el.getAttribute('data-action') || '').split(' ')) {
21+
const [rest, method] = binding.split('#')
1422

15-
// eventName may contain `:` so account for that
16-
// by splitting by the last instance of `:`
17-
const colonIndex = rest.lastIndexOf(':')
18-
if (colonIndex < 0) continue
23+
// eventName may contain `:` so account for that
24+
// by splitting by the last instance of `:`
25+
const colonIndex = rest.lastIndexOf(':')
26+
if (colonIndex < 0) continue
1927

20-
const handler = rest.slice(colonIndex + 1)
21-
if (handler !== tag) continue
28+
const handler = rest.slice(colonIndex + 1)
29+
if (handler !== tag) continue
2230

23-
const eventName = rest.slice(0, colonIndex)
31+
const eventName = rest.slice(0, colonIndex)
2432

25-
// Check the `method` is present on the prototype
26-
const methodDescriptor = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(controller), method)
27-
if (methodDescriptor && typeof methodDescriptor.value == 'function') {
28-
el.addEventListener(eventName, (event: Event) => {
29-
;(controller as any)[method](event)
30-
})
31-
}
33+
// Check the `method` is present on the prototype
34+
const methodDescriptor = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(controller), method)
35+
if (methodDescriptor && typeof methodDescriptor.value == 'function') {
36+
el.addEventListener(eventName, (event: Event) => {
37+
;(controller as any)[method](event)
38+
})
3239
}
3340
}
3441
}

0 commit comments

Comments
 (0)