diff --git a/src/helpers.js b/src/helpers.js index 5d6acaa..9eb325a 100644 --- a/src/helpers.js +++ b/src/helpers.js @@ -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)) }) } @@ -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() @@ -314,7 +314,7 @@ export default class Helpers { App.currentElement = null App.currentEvent = null - }) + }, options) } // Ajax diff --git a/tests/helpers.test.js b/tests/helpers.test.js index dead671..589bac2 100644 --- a/tests/helpers.test.js +++ b/tests/helpers.test.js @@ -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) }) }) })