Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access a function object from within?

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? */);
});
like image 903
yzn-pku Avatar asked Jan 18 '26 15:01

yzn-pku


2 Answers

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 });
like image 114
Quentin Avatar answered Jan 20 '26 05:01

Quentin


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.

like image 41
Eric Avatar answered Jan 20 '26 04:01

Eric



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!