yzn-pku yzn-pku - 1 month ago 13
Javascript Question

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? */);
});

Answer

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 });