|
4 | 4 | */ |
5 | 5 | export function bind(controller: HTMLElement) { |
6 | 6 | 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)) { |
8 | 10 | // Ignore nested elements |
9 | 11 | 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() |
10 | 18 |
|
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('#') |
14 | 22 |
|
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 |
19 | 27 |
|
20 | | - const handler = rest.slice(colonIndex + 1) |
21 | | - if (handler !== tag) continue |
| 28 | + const handler = rest.slice(colonIndex + 1) |
| 29 | + if (handler !== tag) continue |
22 | 30 |
|
23 | | - const eventName = rest.slice(0, colonIndex) |
| 31 | + const eventName = rest.slice(0, colonIndex) |
24 | 32 |
|
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 | + }) |
32 | 39 | } |
33 | 40 | } |
34 | 41 | } |
0 commit comments