Namespace: Events:once

Events:once

Source:

Methods

once(targets, events, handler, optionsopt) → {function}

Registers (an) event listener(s) to (a) valid EventTarget(s) (most likely (a) DOM-element(s)).

This version automatically removes the handler, after it has fired once.

This method is inspired by jQuery and cash, though not identical. You may define one or more targets as well as one or more events to register a handler to, by either providing single arguments or arrays. You may also, additionally, namespace events, like in jQuery/cash, by adding it after the event name, separated by a dot ('click.namespace').

This method returns a remover function, which removes all event registrations done by this method call. So, in essence, calling that function, removes exactly, what was added, in a single call.

Parameters:
Name Type Attributes Default Description
targets EventTarget | Array.<EventTarget>

the target(s) to register event handlers on

events String | Array.<String>

the event name(s) to listen to, can be either a single name or a list of names, each name may also have a namespace, separated by a dot, to target all events/namespaces, you may use ""/".*"

handler function

the callback to execute if the event(s) defined in events are being received on target

options Object | Boolean <optional>
null

event listener options according to "addEventListener"-syntax, will be ignored, if browser does not support this, if boolean, will be used as "useCapture", the same will happen if options are not supported, but you defined "{capture : true}", "{once : true}" makes no sense in this case, because the behaviour will automatically be applied anyway

Source:
See:
Throws:
  • error in case no targets are defined

  • error in case no events are defined

  • error in case handler is not a function

  • error in case targets are not all usable event targets

  • error in case delegations are missing viable ancestor targets

Returns:
remover function, which removes all handlers again, added by the current execution
Type
function
Example
once(linkElement, 'click', e => {	e.stopPropagation(); });
once(someElementWithCustomEvents, 'crash.test', () => { alert('crashed!'); });
once([ancestorElement, 'a'], 'click', e => { e.target.classList.add('clicked'); });
once(buttonElement, 'click', () => { console.log('click twice, but I'll just print once); }, {passive : true});
once([ancestorElement, '.btn[data-foobar="test"]'], 'click', () => { console.log('I'll just fire once); });
once(document.body, 'click', e => { console.log(`oh, a bubbled event, let's see what has been clicked: "${e.target}"`); });
once([foo, foo, 'button', bar], ['mousedown', 'touchstart'], e => { e.target.classList.add('interaction-start'); });