1

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

Peterd
  • 13
  • 4
  • You should be able to test that. Cause some log output with the event handler, remove the entity and fire the event. – lupz Nov 25 '16 at 09:30
  • Agreed, but I couldn't come up with any event I could trigger once the entity is gone. click, hover, etc won't work. – Peterd Nov 28 '16 at 07:55

1 Answers1

3

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.

Community
  • 1
  • 1
Don McCurdy
  • 10,975
  • 2
  • 37
  • 75
  • Thanks, this was what I expected as well. Although I need to test (2). It kind of contradicts (1). When the entity is removed, the eventlisteners (on the entity) should be cleared. So even though we have an external reference to the entity, according to (1), the listeners should be cleared. I'll post my test result later. – Peterd Dec 01 '16 at 09:12
  • Doing this: `el.remove(); cache.el = el;` the browser will not automatically clean up event listeners. If that element is re-attached to DOM, and `init()` binds event listeners again, you'll have duplicate listeners. If your JS discards all references to `el`, then the browser does clean up event listeners (and it's impossible for `el` to be reattached anyway). – Don McCurdy Dec 01 '16 at 14:54