Add listenOnce
This commit is contained in:
26
snippets/listenOnce.md
Normal file
26
snippets/listenOnce.md
Normal 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
|
||||
```
|
||||
@ -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.
|
||||
|
||||
@ -22,4 +23,4 @@ const fn = () => console.log('!');
|
||||
on(document.body, 'click', fn); // logs '!' upon clicking the body
|
||||
on(document.body, 'click', fn, { target: 'p' }); // logs '!' upon clicking a `p` element child of the body
|
||||
on(document.body, 'click', fn, { options: true }); // use capturing instead of bubbling
|
||||
```
|
||||
```
|
||||
|
||||
Reference in New Issue
Block a user