简体   繁体   English

从动态元素中删除onClick

[英]removing onClick from dynamic elements

Should I be removing dynamic clickHandlers to the dynamically created html tags or is it taken care of automatically by the garbage collector. 我应该将动态clickHandlers移除到动态创建的html标签,还是由垃圾收集器自动处理。

My primary browser is Safari (embedded in iOS app), but I think i read that IE has memory leak problem around this. 我的主要浏览器是Safari(内置于iOS应用中),但我想我读到IE对此存在内存泄漏问题。

var li = document.createElement('li');
li.addEventListener('click', function(){});

so if this element was removed from DOM later on, should I delete the clickHandler, just in case please let me know how to property delete a clickHandler? 因此,如果此元素稍后从DOM中删除,我是否应该删除clickHandler,以防万一,请让我知道如何属性删除clickHandler?

li.removeEventListener("click", function_name);

This will remove the event listener 这将删除事件监听器

Source: http://www.w3schools.com/jsref/met_element_removeeventlistener.asp 资料来源: http : //www.w3schools.com/jsref/met_element_removeeventlistener.asp

For anonymous functions, the point of them is really to have no reference and lacks a name, so for removeEventListener() you will need a named function. 对于匿名函数,它们的重点实际上是没有引用且没有名称,因此对于removeEventListener()您将需要一个命名函数。

If there are no references remaining to the element after you remove it, the GC should clean up handler functions that it references. 如果在删除元素后没有剩余对元素的引用,则GC应该清除它引用的处理程序函数。 So you shouldn't need to do anything. 因此,您无需执行任何操作。

But if IE has a bug along this way, you can use removeEventListener to remove the handler, but this requires that you use a named function, since you have to give the same function to removeEventListener as you did when you called addEventListener , and anonymous functions will never be the same as each other. 但是,如果IE出现这种错误,则可以使用removeEventListener删除处理程序,但这要求您使用命名函数,因为必须像调用addEventListener和匿名函数时一样,将相同的函数提供给removeEventListener永远不会彼此相同。

function myClickHandler {
    ...
}
var li = document.createElement('li');
li.addEventListener('click', myClickHandler);
...
li.removeEventListener('click', myClickHandler);
myClickHandler = null;
li.parentNode.removeChild(li);

myClickHandler = null; is needed because otherwise the function name will hold a reference to the handler function, so it won't be GCed. 是必需的,因为否则函数名将包含对处理程序函数的引用,因此不会被GC化。

If you have multiple LIs, and they're all using the same handler function, it shouldn't be necessary to do this. 如果您有多个LI,并且它们都使用相同的处理函数,则不必这样做。 No matter how many LIs you have, they're all just referring to the same function, so it doesn't take up lots of memory. 不管您有多少个LI,它们都只是引用相同的功能,因此不会占用大量内存。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM