TIL — Removing DOM Event Handlers using AbortController
Thanks to Dan, who recommended “AbortController is your friend” by Sam Thorogood, today I learned about the ability to remove DOM event handlers using AbortController. Sam’s article is full of good use cases for this controller, but this one blew my mind.
const controller = new AbortController();
document.addEventListener(
"mousemove",
() => {
// do some cool things here
},
{ signal: controller.signal }
);
// later on
controller.abort();
Look at this example that tracks a mousemove
event on the document
, prints the coordinates and can be aborted on demand by clicking a button. So nice!
See the Pen 2022-06-18 by Pawel Grzybek (@pawelgrzybek) on CodePen.
What is the difference between this and removeEventListener
It is going to be easier to explain using a snippet.
This is really nice example, but kind of unintuitive to use.
Brilliant! had no idea this was possible!