Removing anonymous event listeners

Warning This article was written over six months ago, and may contain outdated information.

I recent­ly ran into a prob­lem involv­ing the removeEventListener() method, which caused me a good half an hour of con­fu­sion before a light­bulb appeared above my head and I was enlight­ened by a solu­tion — a solu­tion which, it must be said, is very obvi­ous in hind­sight. So doubt­less many peo­ple know this already, but I’m record­ing it here along with anoth­er approach I thought of after­wards, in the hope that they may be use­ful to some­one in the future.

The issue at hand is this: to add an event lis­ten­er to an ele­ment, you use the addEventListener() method with the type of event, and the name of the lis­ten­er — most often, a call to a pre-defined function:

el.addEventListener('click', foo);

When you want to remove the lis­ten­er, you use the removeEventListener() method, with the same argu­ments to ensure that only the spec­i­fied event and lis­ten­er com­bi­na­tion is removed:

el.removeEventListener('click', foo);

Sim­ple. But it becomes less straight­for­ward when you use an anony­mous func­tion as the lis­ten­er, per­haps because you want to call anoth­er func­tion and pass argu­ments to it:

el.addEventListener('click', function() {
  foo(bar,baz);
});

In order to remove this lis­ten­er you have to know the name of it. But it’s anony­mous! What are we to do? The answer is ridicu­lous­ly sim­ple: don’t use anony­mous func­tions. You could instead name the func­tion in the lis­ten­er, then remove it when the func­tion has run:

el.addEventListener('click', function _func() {
  foo(bar,baz);
  el.removeEventListener('click', _func);
});

Alter­na­tive­ly, you could assign the func­tion to a vari­able, then use that vari­able as the listener:

var _func = function() {
  foo(bar,baz);
}
el.addEventListener('click', _func);

And remove it by using the vari­able name again:

el.removeEventListener('click', _func);

These solu­tions seem so obvi­ous that I debat­ed whether it was worth record­ing them here, but in my search­es I could­n’t find them list­ed any­where; I hope that by writ­ing them up I’ll save some­one some search­ing time in the future.

3 comments on
“Removing anonymous event listeners”

  1. The final sug­ges­tion of assign­ing the func­tion to a vari­able won’t work in all cas­es. Main­ly because “_func.name == undefined”.

  2. […] Remov­ing anony­mous event lis­ten­ers (Bro­ken Links) […]

  3. “These solu­tions seem so obvi­ous that I debat­ed whether it was worth record­ing them here”.… 

    :)

    FYI: I actu­al­ly came here think­ing you had (mag­i­cal­ly) found a way to do the impossible.…