Anonimowy EventListener można "usunąć" też za pomocą: AbortController.abort() i trzeciego parametru o nazwie signal
addEventListener(type, listener, options = {signal})
signal Optional
An AbortSignal. The listener will be removed when the given AbortSignal object's abort() method is called. If not specified, no AbortSignal is associated with the listener.
przykład
<body data-counter="0"></body>
body {
margin: 0;
width: 100vw;
height: 100vh;
background-color: white;
transition: background 400ms;
}
body:active {
background-color: gray;
}
body:before {
position: absolute;
top: 1em;
left: 1em;
content: attr(data-counter);
font: 700 1em/1.1 system-ui;
}
let i=0;
const controller = new AbortController();
document.querySelector('body').addEventListener('click', _=> {
document.body.dataset.counter = ++i;
// remove listener gdy "i" osiągnie wartość większą od 9
if (i > 9) controller.abort();
}, {signal: controller.signal});