@elitastic gave a correct answer.
You should note that functions are values in JavaScript as well. (They are instances of the Function
class.) If you tried to pass anonymous functions to addEventListener
and removeEventListener
, JavaScript would handle those two anonymous functions as two independent values, even if they have the same signature and body. So that does not work as expected.
So you are right that you need to name your function. (Or assign it to a variable, which is effectively the same.)
@elitastic introduced a class member called onEvent
in his answer, which refers to the desired event listener function to use. By using that single onEvent
variable in both the addEventListener
and removeEventListener
calls, it will work as expected.
As you can see, it is quite fine to assign arrow functions to variables as well. @elitastic’s solution might even work with a regular function, but then you will need to explicitly bind that function to the class instance for the this
keyword to work correctly. Something like this:
onEvent = (function (this, event) {
this.eventHandler(event.detail);
}).bind(this);
Personally, I prefer arrow functions here.