Reputation: 1082
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? */);
});
Upvotes: 2
Views: 51
Reputation: 97575
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.
Upvotes: 4
Reputation: 1074058
You can give the function a name that isn't in scope anywhere except inside it:
var someButton;
someButton.addEventListener("click", function handler() {
console.log("clicked");
someButton.removeEventListener("click", handler);
});
That doesn't create a handler
identifier binding in the scope where someButton
is. (Historical note: IE8 and earlier had a bug where it did.)
If you really don't want to do that, and you don't mind using loose mode and using things that are deprecated, you could use arguments.callee
instead:
// NOT RECOMMENDED AT ALL. WILL NOT WORK IN STRICT MODE.
var someButton;
someButton.addEventListener("click", function() {
console.log("clicked");
someButton.removeEventListener("click", arguments.callee);
});
Upvotes: 3
Reputation: 943163
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 });
Upvotes: 5