Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why call removeEventListener inside addEventListener callback?

I have downloaded a JS starter template. It has a default.js file like this: (Of course the js file is referenced in an html page that contains just an <a> element.)

(function () {
    "use strict";
    window.addEventListener("load", function load(event) {
        window.removeEventListener("load", load, false);
        init();
    }, false);

    function init() {
        document.getElementById("link").addEventListener("click", showAlert, false);
    }

    function showAlert() {
        alert("Welcome to Pure HTML!");
    }
}());

Now my question is why there is a window.removeEventListener in the window.addEventListener function?

like image 868
Siavash Mortazavi Avatar asked May 22 '14 11:05

Siavash Mortazavi


People also ask

What is removeEventListener?

The removeEventListener() is an inbuilt function in JavaScript which removes an event handler from an element for a attached event. for example, if a button is disabled after one click you can use removeEventListener() to remove a click event listener.

Are event listeners callbacks?

The event listener callbackThe event listener can be specified as either a callback function or an object whose handleEvent() method serves as the callback function.

Is addEventListener a callback function?

addEventListener('click',callback); In the above code, we add addEventListener as a function and we are passing another function callback as an argument. And when a click event is triggered the addEventListener registers the callback function.

Why do we need to remove event listeners?

Since we only need the listener for our modal, it should be removed whenever the user cannot interact with our modal any longer. The same is true for any element that can be toggled as well as animations on elements.


1 Answers

It is a pattern for allowing an event handler to execute once. In the first execution of the event handler, the event handler is removed to stop it executing again.

It's interesting this is used for the window load event, as that should only fire once anyway.

like image 92
2 revs Avatar answered Sep 17 '22 12:09

2 revs