Hello, my name is: Amy

Removing an event listener added with bind

Generally speaking, I'm not great at removing event listeners after they have been added. I do get myself into a few situations where it's unavoidable, and most all of these have been around using transitionend.

I find the transitionend event incredibly helpful when doing things like animating something out of the window and then (once the animation has smoothly finished) make the element display: none so the element is no longer able to be tabbed through.

Removing an Event listener

Generally speaking, you can remove an event listener similarly to how you'd add one. The listener function has to be a reference to the same one used to add the event. Because of this, you're not able to use an anonymous function when you add an event that needs to be removed.

var el = document.querySelector('.box');
function doSomething (e) { console.log('things are happening'); }

el.addEventListener('mouseover', doSomething);

// remove mouseover event when clicked
el.addEventListener('click', function() {
  el.removeEventListener('mouseover', doSomething);
});

Removing an Event listener added with Bind

A lot of the code I write now tends to have each functionality contained w/in an object. This was giving me a ton of problems because I couldn't figure out how to have a reference to the object, and a reference to the function itself.

It turns out, using bind creates a new function reference, so I wasn't just referencing the same function when I removed it. In order to have a bound function, that would stay the same you have to assign that bound function reference to a new variable than can be referenced when it's time to remove.

In this example below, if I don't remove the transitionend event, then it would fire one the 'un-squish' as well.

See the Pen RemoveEventListener in added with Bind by Amy Etheredge (@theaemarie) on CodePen.

Also (certainly not that I'm speaking from experience) make sure you spell transitionend correctly.

Comments