Skip to content

Commit

Permalink
Fix trouble combining keyup event, key name and modificator "once" (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
lozunoff committed Mar 21, 2022
1 parent 0d1731b commit c670b9f
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 8 deletions.
16 changes: 8 additions & 8 deletions packages/alpinejs/src/utils/on.js
Expand Up @@ -40,6 +40,14 @@ export default function on (el, event, modifiers, callback) {
})
}

if (modifiers.includes('once')) {
handler = wrapHandler(handler, (next, e) => {
next(e)

listenerTarget.removeEventListener(event, handler, options)
})
}

// Handle :keydown and :keyup listeners.
handler = wrapHandler(handler, (next, e) => {
if (isKeyEvent(event)) {
Expand All @@ -65,14 +73,6 @@ export default function on (el, event, modifiers, callback) {
handler = throttle(handler, wait)
}

if (modifiers.includes('once')) {
handler = wrapHandler(handler, (next, e) => {
next(e)

listenerTarget.removeEventListener(event, handler, options)
})
}

listenerTarget.addEventListener(event, handler, options)

return () => {
Expand Down
19 changes: 19 additions & 0 deletions tests/cypress/integration/directives/x-on.spec.js
Expand Up @@ -239,6 +239,25 @@ test('.once modifier with @keyup',
}
)

test('.once modifier with @keyup and specified key',
html`
<div x-data="{ count: 0 }">
<input type="text" x-on:keyup.enter.once="count = count+1">
<span x-text="count"></span>
</div>
`,
({ get }) => {
get('span').should(haveText('0'))
get('input').type('f')
get('span').should(haveText('0'))
get('input').type('{enter}')
get('span').should(haveText('1'))
get('input').type('{enter}')
get('span').should(haveText('1'))
}
)

test('.debounce modifier',
html`
<div x-data="{ count: 0 }">
Expand Down

0 comments on commit c670b9f

Please sign in to comment.