yzn-pku yzn-pku - 1 year ago 98
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() {
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() {
someButton.removeEventListener("click", /* what goes here? */);

Answer Source

You need to give it a name. You can use a named function expression though.

someButton.addEventListener("click", function foo () {
  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 () {
}, { once: true });
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download