Add listenOnce

This commit is contained in:
Angelos Chalaris
2020-06-01 16:58:52 +03:00
parent 0d5ccc925d
commit 125fda22f3
2 changed files with 29 additions and 2 deletions

26
snippets/listenOnce.md Normal file
View File

@ -0,0 +1,26 @@
---
title: listenOnce
tags: browser,event,intermediate
---
Adds an event listener to an element that will only run the callback the first time the event is triggered.
Use `EventTarget.addEventListener()` to add an event listener to an element, storing the reference in a variable.
Use `EventTarget.removeEventListenre()` to remove the listener after the first time the event is triggered.
```js
const listenOnce = (el, evt, fn) => {
const listener = el.addEventListener(evt, (e) => {
fn(e);
el.removeEventListener(evt, listener);
});
};
```
```js
listenOnce(
document.getElementById('my-id),
'click',
() => console.log('Hello world')
); // 'Hello world' will only be logged on the first click
```

View File

@ -5,7 +5,8 @@ tags: browser,event,intermediate
Adds an event listener to an element with the ability to use event delegation.
Use `EventTarget.addEventListener()` to add an event listener to an element. If there is a `target` property supplied to the options object, ensure the event target matches the target specified and then invoke the callback by supplying the correct `this` context.
Use `EventTarget.addEventListener()` to add an event listener to an element.
If there is a `target` property supplied to the options object, ensure the event target matches the target specified and then invoke the callback by supplying the correct `this` context.
Returns a reference to the custom delegator function, in order to be possible to use with [`off`](#off).
Omit `opts` to default to non-delegation behavior and event bubbling.