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("Wele to Pure HTML!");
}
}());
Now my question is why there is a window.removeEventListener
in the window.addEventListener
function?
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("Wele to Pure HTML!");
}
}());
Now my question is why there is a window.removeEventListener
in the window.addEventListener
function?
- 2 Immediately-Invoked Function Expression (IIFE) – adeneo Commented May 22, 2014 at 11:46
1 Answer
Reset to default 13It 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.