Update listenOnce.md

This commit is contained in:
Angelos Chalaris
2020-06-03 13:39:34 +03:00
committed by GitHub
parent 60d2238718
commit 4c6541be33

View File

@ -1,18 +1,19 @@
--- ---
title: listenOnce title: listenOnce
tags: browser,event,intermediate tags: browser,event,closure,intermediate
--- ---
Adds an event listener to an element that will only run the callback the first time the event is triggered. 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.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. Use a condition to call `fn` only the first time the listener is triggered.
```js ```js
const listenOnce = (el, evt, fn) => { const listenOnce = (el, evt, fn) => {
const listener = el.addEventListener(evt, (e) => { let fired = false;
fn(e); el.addEventListener(evt, (e) => {
el.removeEventListener(evt, listener); if (!fired) fn(e);
fired = true;
}); });
}; };
``` ```