30秒学会 JavaScript 片段 · 2019年1月15日

30秒学会 JavaScript 片段 – listenOnce

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 a condition to call fn only the first time the listener is triggered.

代码片段

const listenOnce = (el, evt, fn) => {
  let fired = false;
  el.addEventListener(evt, (e) => {
    if (!fired) fn(e);
    fired = true;
  });
};

使用样例

listenOnce(
  document.getElementById('my-id),
  'click',
  () => console.log('Hello world')
); // 'Hello world' will only be logged on the first click