2

I looked at the post When do I need to call removeEventListener in my components? but it did not address my question.

I've heard that its best practice to removeEventListener on pause and addEventListener on play in order to maintain consistent (to other components) click functionality while using the A-Frame inspector. Thus your code would look like this:

AFRAME.registerComponent('my-component', {
  init: function() {
    this.doSomething = function() {
      console.log("I'm doing it")
    }
  },
  play: function() {
    this.el.addEventListener('click', this.doSomething)
  },
  pause: function() {
    this.el.removeEventListener('click', this.doSomething)
  }
})

It seems to me that if the A-Frame inspector needs this to be done to work properly, then it should handle this for me instead of making me do it for every event listener I add. Is there any merit to this claim?

Other than the A-Frame Inspector aspect, could there be a situation where code running in an event handler while the scene is partially initialized or partially destroyed could cause hard to diagnose bugs?

Becca
  • 143
  • 1
  • 6

1 Answers1

0

The important pieces are:

  1. That the event listeners get cleaned up after the entity is removed or detached from the scene. When entities get removed, not only is the .remove handler called, but so is the .pause handler.

  2. Yes, so the event listeners don't run when the Inspector is open. This might not be as important within the context of an application, but useful to implement if you are sharing a generalized component where people might use the Inspector to poke around.

In any case, if you're going to add event listeners, you might as well use .play and .pause. It doesn't hurt and make sure things run cleanly in every case.

ngokevin
  • 12,980
  • 2
  • 38
  • 84