Skip to content
Advertisement

Removing event listener which was added with bind

In JavaScript, what is the best way to remove a function added as an event listener using bind()?

Example

JavaScript

The only way I can think of is to keep track of every listener added with bind.

Above example with this method:

JavaScript

Are there any better ways to do this?

Advertisement

Answer

Although what @machineghost said was true, that events are added and removed the same way, the missing part of the equation was this:

A new function reference is created after .bind() is called.

See Does bind() change the function reference? | How to set permanently?

So, to add or remove it, assign the reference to a variable:

JavaScript

This works as expected for me.

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