Things I want to do
When using JavaScript to trigger events and perform actions, you typically use `addEventListener`, but sometimes you only want it to execute once (for example, when an event is ready to be triggered).
Using `removeEventListener` would work, but it’s troublesome because you have to set up the exact same listener. (I messed up during maintenance.)
This article explains how to perform an action only once without using removeEventListener.
implementation
Normally, addEventListener would be written as follows.
element.addEventListener(event, callback);
// example
// element.addEventListener("click", ()=>{console.log("clicked")});With this implementation, the callback will be executed every time an event occurs.
We will modify this implementation as follows:
element.addEventListener(event, callback, {once: true});If the third argument before the modification was true
It will be as follows:
Before revision
element.addEventListener(event, callback, true);After correction
element.addEventListener(event, callback, {once: true, capture :true});Result
The listener set with addEventListener will now be executed only once.
Websites I used as references
EventTarget: addEventListener() メソッド - Web API | MDN
addEventListener() は EventTarget インターフェイスのメソッドで、ターゲットに特定のイベントが配信されるたびに呼び出される関数を設定します。


コメント