什么时候需要在组件中调用removeEventListener? [英] When do I need to call removeEventListener in my components?

查看:170
本文介绍了什么时候需要在组件中调用removeEventListener?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

文档中提到我可以使用组件的删除功能来删除我添加的事件侦听器。我一直都需要吗?还是在删除实体时删除了事件?

The documentation mentions that I could use the remove function of the components to remove eventlisteners I have added. Do I need to this at all times? Or are events removed when the entity is removed?

我知道我需要删除在其他实体上添加的事件。但是,如果组件将click事件添加到其实体。移除实体后,该点击事件会被移除吗?还是这会导致内存泄漏?

I understand that I need to remove events I have added on other entities. But if the component adds a click event to its entity. Will that click event be removed when the entity is removed? Or can this cause a memory leak?

欢呼

Peter

推荐答案

这里要考虑三种情况:


  1. 如果是DOM元素(例如A-Frame的< a-entity /> )是分离的,并且您没有在任何地方将对元素的引用存储在变量中,那么您不会无需解除绑定事件监听器-侦听器会自动清理

  1. If a DOM element (like A-Frame's <a-entity/>) is detached, and you don't store a reference to the element in a variable anywhere, then you don't need to unbind your event listeners — the listeners are cleaned up automatically.

如果要存储元素以便以后重新附加,则需要在 remove()中删除​​侦听器,以便下次 init()运行时,您不会开始接收重复的事件

If you're storing the element to re-attach it later, then you would want to remove listeners in remove() so that the next time init() runs, you don't start receiving duplicate events.

最后一种情况,可能是最重要的情况是,如果您的组件将侦听器绑定到其自身之外的其他元素(画布文档正文),那么您肯定要清理监听器,以使回调不会触发不再存在的组件。

The final case, and probably the most important, is that if your component binds listeners to elements other than its own (the canvas, document, or body for example) then you definitely want to clean up your listeners so that your callbacks won't fire for a component that is no longer in the scene.

这篇关于什么时候需要在组件中调用removeEventListener?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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