Skip to content

Commit e34a50f

Browse files
dgrahamkeithamus
andcommitted
Introduce Binding type
Co-authored-by: Keith Cirkel <keithamus@users.noreply.github.com>
1 parent dcfa7fe commit e34a50f

1 file changed

Lines changed: 19 additions & 22 deletions

File tree

src/bind.ts

Lines changed: 19 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -58,38 +58,35 @@ function bindElements(root: Element) {
5858
}
5959
}
6060

61-
function getActionEventName(action: string): string {
62-
return action.slice(0, action.lastIndexOf(':'))
63-
}
64-
65-
function getActionControllerName(action: string): string {
66-
return action.slice(action.lastIndexOf(':') + 1, action.lastIndexOf('#'))
67-
}
68-
69-
function getActionMethodName(action: string): string {
70-
return action.slice(action.lastIndexOf('#') + 1)
71-
}
72-
7361
// Bind a single function to all events to avoid anonymous closure performance penalty.
7462
function handleEvent(event: Event) {
7563
const el = event.currentTarget
7664
if (!(el instanceof Element)) return
77-
for (const action of (el.getAttribute('data-action') || '').split(' ')) {
78-
if (event.type !== getActionEventName(action)) continue
79-
const tagName = getActionControllerName(action)
65+
for (const binding of bindings(el)) {
8066
// Dispatch only to Catalyst elements.
81-
if (!controllers.has(tagName)) continue
82-
const controller = el.closest(tagName) as Element & Record<string, (ev: Event) => unknown>
67+
if (event.type !== binding.type || !controllers.has(binding.tag)) continue
68+
const controller = el.closest(binding.tag) as Element & Record<string, (ev: Event) => unknown>
8369
if (!controller) continue
84-
const method = getActionMethodName(action)
85-
if (typeof controller[method] === 'function') {
86-
controller[method](event)
70+
if (typeof controller[binding.method] === 'function') {
71+
controller[binding.method](event)
8772
}
8873
}
8974
}
9075

76+
type Binding = {type: string; tag: string; method: string}
77+
function bindings(el: Element): Binding[] {
78+
return (el.getAttribute('data-action') || '').split(' ').map(action => {
79+
const eventSep = action.lastIndexOf(':')
80+
const methodSep = action.lastIndexOf('#')
81+
const type = action.slice(0, eventSep)
82+
const tag = action.slice(eventSep + 1, methodSep)
83+
const method = action.slice(methodSep + 1)
84+
return {type, tag, method}
85+
})
86+
}
87+
9188
function bindActions(el: Element) {
92-
for (const action of (el.getAttribute('data-action') || '').split(' ')) {
93-
el.addEventListener(getActionEventName(action), handleEvent)
89+
for (const binding of bindings(el)) {
90+
el.addEventListener(binding.type, handleEvent)
9491
}
9592
}

0 commit comments

Comments
 (0)