Darvlaskie
Darvlaskie

Reputation: 43

Importance of removeEventListener? AS3

I have a few questions about Event Listeners. Please answer them clearly.

  1. Do we always need to removeEventListener every time we do addEventListener?
  2. When removing an object from stage, does it also remove its eventlisteners? Example, lets say i have a textfield with event listener like the one below.

    txtField1.addEventListener(Event.CHANGE, F_onCHange_TxtField);

I have a code that removes the textfield from stage my question is this: In removing the textfield, does it also remove the eventListener automatically?

  1. When removing eventListeners, does it help enhance performance or maybe something else?

Upvotes: 1

Views: 447

Answers (1)

Paul Mignard
Paul Mignard

Reputation: 5924

Here are my answers, let me know if you have any questions!

  1. Well, not exactly. But if there is an active event listener on an object it will never be garbage collected. It's preferable to explicitly remove the event listener but at the very least use weak listeners like this:

    myThing.addEventListener(Event.Complete, Handler, false, 0, true);

The last parameter is what makes it weak.

  1. No, and this is what ties back into your first question. After the object has been removed from the stage it still exists in memory. If you have a strong event listener on it it'll remain there. If you put it back on the stage the it'll still respond to whatever events it's listening for.

  2. Removing event listeners has more to do with resource management but if you have an instance where you're creating new objects regularly and creating event listeners you'll definitely want to make sure to clean them up to prevent holding onto all of those objects during the life of your application.

I hope this helped! Grant Skinner has some great articles on this, I highly recommend you check them out. Start Here!

Upvotes: 3

Related Questions