|
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 | + // Also bind the controller to itself |
| 16 | + if (controller.matches(actionAttributeMatcher)) { |
| 17 | + bindActionsToController(controller, controller) |
| 18 | + } |
| 19 | +} |
| 20 | + |
| 21 | +// Bind the data-action attribute of a single element to the controller |
| 22 | +function bindActionsToController(controller: HTMLElement, el: Element) { |
| 23 | + const tag = controller.tagName.toLowerCase() |
| 24 | + |
| 25 | + // Match the pattern of `eventName:constructor#method`. |
| 26 | + for (const binding of (el.getAttribute('data-action') || '').split(' ')) { |
| 27 | + const [rest, method] = binding.split('#') |
| 28 | + |
| 29 | + // eventName may contain `:` so account for that |
| 30 | + // by splitting by the last instance of `:` |
| 31 | + const colonIndex = rest.lastIndexOf(':') |
| 32 | + if (colonIndex < 0) continue |
| 33 | + |
| 34 | + const handler = rest.slice(colonIndex + 1) |
| 35 | + if (handler !== tag) continue |
| 36 | + |
| 37 | + const eventName = rest.slice(0, colonIndex) |
10 | 38 |
|
11 | | - // Match the pattern of `eventName:constructor#method`. |
12 | | - for (const binding of (el.getAttribute('data-action') || '').split(' ')) { |
13 | | - const [rest, method] = binding.split('#') |
14 | | - const [eventName, handler] = rest.split(':') |
15 | | - if (handler !== tag) continue |
16 | | - |
17 | | - // Check the `method` is present on the prototype |
18 | | - const methodDescriptor = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(controller), method) |
19 | | - if (methodDescriptor && typeof methodDescriptor.value == 'function') { |
20 | | - el.addEventListener(eventName, (event: Event) => { |
21 | | - ;(controller as any)[method](event) |
22 | | - }) |
23 | | - } |
| 39 | + // Check the `method` is present on the prototype |
| 40 | + const methodDescriptor = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(controller), method) |
| 41 | + if (methodDescriptor && typeof methodDescriptor.value == 'function') { |
| 42 | + el.addEventListener(eventName, (event: Event) => { |
| 43 | + ;(controller as any)[method](event) |
| 44 | + }) |
24 | 45 | } |
25 | 46 | } |
26 | 47 | } |
0 commit comments