删除一个DOM对象(在Javascript中)是否会导致内存泄漏,如果它附加事件? [英] Does remove a DOM object (in Javascript) will cause Memory leak if it has event attached?

查看:608
本文介绍了删除一个DOM对象(在Javascript中)是否会导致内存泄漏,如果它附加事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,如果在javascript中,我在HTML页面中创建一个DOM对象,并将事件侦听器附加到DOM对象中,当我从HTML页面中删除DOM时,事件侦听器是否仍然存在并导致内存泄漏?

So, if in the javascript, I create a DOM object in the HTML page, and attach event listener to the DOM object, upon I remove the the DOM from HTML page, does the event listener still exist and causing memory leak?

  function myTest() {
     var obj = document.createElement('div');
     obj.addEventListener('click', function() {alert('whatever'); });
     var body = document.getElementById('body'); // assume there is a <div id='body'></div> already
     body.appendChild(obj);
  }

  // then after some user actions. I call this:
  function emptyPage() {
    var body = document.getElementById('body');
    body.innerHTML = '';  //empty it.
  }

所以,DOM对象< div> 内部正文已经没了。但是, eventlistener 呢?
我只是担心会造成内存泄漏。

So, the DOM object, <div> inside body is gone. But what about the eventlistener? I'm just afraid that it will cause memory leak.

推荐答案

可悲的是,W3C没有一个事件集合,您可以筛选应用于单个元素的所有事件。您可以手动执行(即obj.Events = {}; obj.Events [type] = []; obj.Events [type] .push(fn)为每个添加的事件。事件[types]是一个数组,如果您有多个功能,您希望一次启动,您可以单独删除),然后循环遍历obj.Events对象以删除所有事件,然后再删除对象。

The sad thing is, the W3C does not have an events collection where you can sift through all events applied to a single element. You could do it manually (i.e. obj.Events = {}; obj.Events[type] = []; obj.Events[type].push(fn) for each event that is added. Event[types] is an array so if you have multiple functions you wish to fire at a time, you can remove each individually), then loop through the obj.Events object to remove all events before removing the object.

这篇关于删除一个DOM对象(在Javascript中)是否会导致内存泄漏,如果它附加事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆