From 125fda22f323fd2bbfe54f615f12280f3823acd6 Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Mon, 1 Jun 2020 16:58:52 +0300 Subject: [PATCH] Add listenOnce --- snippets/listenOnce.md | 26 ++++++++++++++++++++++++++ snippets/on.md | 5 +++-- 2 files changed, 29 insertions(+), 2 deletions(-) create mode 100644 snippets/listenOnce.md diff --git a/snippets/listenOnce.md b/snippets/listenOnce.md new file mode 100644 index 000000000..f4afbbc43 --- /dev/null +++ b/snippets/listenOnce.md @@ -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 +``` diff --git a/snippets/on.md b/snippets/on.md index a91d58fde..5c7345718 100644 --- a/snippets/on.md +++ b/snippets/on.md @@ -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 -``` \ No newline at end of file +```