Craig Fisk .co .uk

How to remove an Event Listener without the function declaration

I learned a new feature in Javascript the other day whilst I was working on a new game prototype. My requirement was to have one Event in this case a TouchEnd event call a function to remove a different Event Listener for a TouchMove event.

The regular way of doing this would be by using removeEventListener

See the Pen Simple Remove Event Listener by Craig Fisk (@the_fisk) on CodePen.

This example will remove the touchmove event when the touchend event is fired.

However this does not work if you have to bind the execution context to the listener function as bind creates a new function reference.

There are two ways this can be solved, one of which was new to me:

Old way

See the Pen Bind Event Listener by Craig Fisk (@the_fisk) on CodePen.

This way creates a new function declaration with the bound context and assigns it to a const called boundHandleTouchMove, then this can be used as the reference for add and removeEventListener.

New way

See the Pen Signal Event Listener Removal by Craig Fisk (@the_fisk) on CodePen.

This way we create an AbortController and store a reference to it in the const controller. We then pass a reference to the AbortControllers signal to the event listener via the signal property on the event listeners options parameter. We can then at any point, in this case when handleTouchEnd is called call the controller's abort function which removes the event listener.

This is an interesting way of handling removing event listeners as the reference to the controller can both be stored for a long time as well as called far away from the context of the original addEventListener call as we don't need to know the name of the original event listeners reference to remove it.