Suppose I want to register a single-use event listener on a button, I could write:
var someButton;
var once = function() {
console.log("clicked");
someButton.removeEventListener("click", once);
};
someButton.addEventListener("click", once);
What if I don't even want to give that function a name? Like:
var someButton;
someButton.addEventListener("click", function() {
console.log("clicked");
someButton.removeEventListener("click", /* what goes here? */);
});
You need to give it a name. You can use a named function expression though.
someButton.addEventListener("click", function foo () {
console.log("clicked");
someButton.removeEventListener("click", foo);
});
It will be scoped so it is only accessible from within the function.
Alternatively, use the new (very new, requires Chrome 55 or Firefox 50, no MSIE, Opera or stable Safari support at the time of writing) options syntax for addEventListener:
someButton.addEventListener("click", function () {
console.log("clicked");
}, { once: true });
What if I don't even want to give that function a name? Like:
Just give it a name anyway!
var someButton;
someButton.addEventListener("click", function once() {
console.log("clicked");
someButton.removeEventListener("click", once);
});
This has the added bonus that your stack trace will now show the function name.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With