When do I need to call removeEventListener in my components?

你。 提交于 2019-12-08 12:03:56

问题


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?

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?

Cheers

Peter


回答1:


Three cases to consider here:

  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.

  2. 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.

  3. 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.



来源:https://stackoverflow.com/questions/40801404/when-do-i-need-to-call-removeeventlistener-in-my-components

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!