开发者

Correct way to prevent memory leaks on DOM event listener

开发者 https://www.devze.com 2023-01-14 13:11 出处:网络
Some stupid question about DOM, please don\'t hate me For some reasons I need to pass an anonymous function to addEventListener (mainly to \"pass\" context variables) but the listener once called can

Some stupid question about DOM, please don't hate me

For some reasons I need to pass an anonymous function to addEventListener (mainly to "pass" context variables) but the listener once called can be removed so I want to understand if the code shown below is the correctly way to detach the listener.

    var item = document.createElement("div");
    item.addEventListener("click", function(event) {
        // do some stuff
        // remove listener otherwise we generate a memory leak
       开发者_开发百科 item.removeEventListener("click", arguments.callee, false);
    }, false);

    var menu = document.getElementById("mymenu"); // some element
    menu.appendChild(item);

Another question, if the element menu is removed from its parent using removeChild the listener is removed automatically?


I know you want to use an anonymous function, but you may be better off with a named function; it should still have access to the same outer variables.

Perhaps this:

var item = document.createElement("div");
var listener = function(event) {
        // do some stuff
        // remove listener otherwise we generate a memory leak
        item.removeEventListener("click", listener, false);
    };
item.addEventListener("click", listener, false);

var menu = document.getElementById("mymenu"); // some element
menu.appendChild(item);

Oh, and I don't hate you :)

0

精彩评论

暂无评论...
验证码 换一张
取 消