Skip to content
Advertisement

removeEventListener on anonymous functions in JavaScript

I have an object that has methods in it. These methods are put into the object inside an anonymous function. It looks like this:

JavaScript

(there is a lot more code, but this is enough to show the problem)

Now I want to stop the event listener in some cases. Therefore I am trying to do a removeEventListener but I can’t figure out how to do this. I have read in other questions that it is not possible to call removeEventListener on anonymous functions, but is this also the case in this situation?

I have a method in t created inside the anonymous function and therefore I thought it was possible. Looks like this:

JavaScript

Why can’t I do this?

Is there any other (good) way to do this?

Bonus info; this only has to work in Safari, hence the missing IE support.

Advertisement

Answer

I believe that is the point of an anonymous function, it lacks a name or a way to reference it.

If I were you I would just create a named function, or put it in a variable so you have a reference to it.

JavaScript

You can then remove it by

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement