Skip to content

Commit

Permalink
[Feature] Options added to 'on' helper (#90)
Browse files Browse the repository at this point in the history
  • Loading branch information
franpb14 authored Oct 9, 2024
1 parent 591a788 commit 32fcc47
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 8 deletions.
8 changes: 4 additions & 4 deletions src/helpers.js
Original file line number Diff line number Diff line change
Expand Up @@ -285,12 +285,12 @@ export default class Helpers {
}

// Events
on(query, events, callback) {
on(query, events, callback, options = {}) {
let elements = findAll(query)
if (elements.length == 0) return

elements.forEach(el => {
events.split(' ').forEach(event => _addListener(el, event, callback))
events.split(' ').forEach(event => _addListener(el, event, callback, options))
})
}

Expand All @@ -302,7 +302,7 @@ export default class Helpers {
return App.currentEvent
}

_addListener(elem, event, callback) {
_addListener(elem, event, callback, options) {
elem.addEventListener(event, (e) => {
if (event == 'click' && (['A', 'BUTTON'].includes(elem.tagName) || (elem.tagName == 'INPUT' && elem.type == 'submit')))
e.preventDefault()
Expand All @@ -314,7 +314,7 @@ export default class Helpers {

App.currentElement = null
App.currentEvent = null
})
}, options)
}

// Ajax
Expand Down
22 changes: 18 additions & 4 deletions tests/helpers.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -541,10 +541,24 @@ describe('Events', () => {

on('div', 'click blur', callback)

expect(spyElement).toHaveBeenNthCalledWith(1, 'click', expect.any(Function))
expect(spyElement).toHaveBeenNthCalledWith(2, 'blur', expect.any(Function))
expect(spyElement2).toHaveBeenNthCalledWith(1, 'click', expect.any(Function))
expect(spyElement2).toHaveBeenNthCalledWith(2, 'blur', expect.any(Function))
expect(spyElement).toHaveBeenNthCalledWith(1, 'click', expect.any(Function), {})
expect(spyElement).toHaveBeenNthCalledWith(2, 'blur', expect.any(Function), {})
expect(spyElement2).toHaveBeenNthCalledWith(1, 'click', expect.any(Function), {})
expect(spyElement2).toHaveBeenNthCalledWith(2, 'blur', expect.any(Function), {})
})

test('with "once" option', () => {
const callback = jest.fn()
const spyElement = jest.spyOn(element, 'addEventListener')

on(element, 'click', callback, { once: true })

element.dispatchEvent(new Event('click'))
element.dispatchEvent(new Event('click'))

expect(spyElement).toHaveBeenCalledTimes(1)
expect(spyElement).toHaveBeenCalledWith('click', expect.any(Function), { once: true })
expect(callback).toHaveBeenCalledTimes(1)
})
})
})
Expand Down

0 comments on commit 32fcc47

Please sign in to comment.