admin管理员组文章数量:1386852
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?
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?
Share Improve this question asked Aug 31, 2010 at 15:57 dafidafi 3,5322 gold badges30 silver badges52 bronze badges 1- It seems necessary as reported on Mozilla docs developer.mozilla/en/DOM/… You are right I'm using Firefox ;) – dafi Commented Aug 31, 2010 at 17:59
1 Answer
Reset to default 6I 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 :)
本文标签: javascriptCorrect way to prevent memory leaks on DOM event listenerStack Overflow
版权声明:本文标题:javascript - Correct way to prevent memory leaks on DOM event listener - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744492418a2608816.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论