Only fire an event once?

Viewed 39756

How do I control only firing an event once?

Actually, a quick Google appears to allude to the fact that .one helps..

7 Answers

Just use proper option in your addEventListener method call:

element.addEventListener(event, func, { once: true })

Added the options for add/remove event listener:

function addEventListenerOnce(target, type, listener, optionsOrUseCaptureForAdd, optionsOrUseCaptureForRemove) {
    const f = event => {
        target.removeEventListener(type, f, optionsOrUseCaptureForRemove);
        listener(event);
    }
    target.addEventListener(type, f, optionsOrUseCaptureForAdd);
}
Related