最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Why call removeEventListener inside addEventListener callback? - Stack Overflow

programmeradmin4浏览0评论

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?

Share Improve this question edited Apr 11, 2023 at 9:39 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked May 22, 2014 at 11:43 Siavash MortazaviSiavash Mortazavi 1,8621 gold badge18 silver badges20 bronze badges 1
  • 2 Immediately-Invoked Function Expression (IIFE) – adeneo Commented May 22, 2014 at 11:46
Add a ment  | 

1 Answer 1

Reset to default 13

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.

发布评论

评论列表(0)

  1. 暂无评论