LoginSignup
8
9

More than 5 years have passed since last update.

JavaScriptで一回だけ実行するイベントを登録する(jQueryの`one`メソッド風)

Last updated at Posted at 2017-01-18

JavaScriptで一回だけ実行させるeventをbindしたかったが、
jQueryのoneのようなメソッドがなかったので同様の処理を行うaddEventListenerOnceを実装した。

addEventListenerのoptionsパラメータが使用できるブラウザなどでは、
onceパラメータを使用する。
https://developer.mozilla.org/ja/docs/Web/API/EventTarget/addEventListener

addEventListener('click', () => {
  // 処理
}, { once: true});

addEventListenerのoptionsパラメータが使用できない場合は、
下記コードを参照。

Code(ES6)

const addEventListenerOnce = (target, type, listener) => {
  target.addEventListener(type, function fn() {
    target.removeEventListener(type, fn);
    listener();
  });
};

const element = document.getElementById('sample');
addEventListenerOnce(element, 'click', () => {
    // 処理...
});

Code

var addEventListenerOnce = function(target, type, listener) {
  target.addEventListener(type, function fn() {
    target.removeEventListener(type, fn);
    listener();
  });
};

var element = document.getElementById('sample');
addEventListenerOnce(element, 'click', function() {
    // 処理...
});

8
9
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
9