When do I need to call removeEventListener in my c

2019-06-14 12:16发布

问题:

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.



标签: aframe