Abin Mathew Abraham
Abin Mathew Abraham

Reputation: 170

Does existing event listeners prevent proper disposal of objects?

I have a Main class and another class say "A".

public class A extends MovieClip
{
    private var z : int;
    private var y : String;

    public function A(param1 : int, param2 : String)
    {
        z = param1;
        y = param2
        Stage.addEventListener(eventString, functionToBeTriggered);
    }

    private function functionToBeTriggered(evt : EventType) : void
    {
       trace(z+"....."+y);
    }
}

I create objects of Class A from Main Class. I also dispose these objects properly. Inside Class A, I added an event listener for Stage and I forgot to remove it when i disposed Class A's object. Every time when I create an object of Class A from Main Class, the listeners on Stage increases. The function executed on listening uses 'z' and 'y' variables of the object.

These are the steps that I used :-

    1) I create an object say "objA" of Class A; Stage has 1 event listener.
    2) I dispose "objA"; but Stage still has 1 event listener.
    3) I create another object say "objB" of Class A; Stage now has 2 event Listeners.
    4) I dispatch the event to trigger functionToBeTriggered; Now 2 function are triggered one of objA and another of objB; I got 'z' and 'y' of both objA and objB

These are my doubts:-

    1) As I have disposed objA before creating objB ie. I did objA = null; how did i get the value of 'z' and 'y' of objA?
    2) Is an active Listener preventing me from proper disposal of object?
    3) How do I clear references of primitive data types like int and String etc ?

I hope I have conveyed my question clearly. Please do help.

Upvotes: 0

Views: 621

Answers (1)

Daniel MesSer
Daniel MesSer

Reputation: 1181

By calling addEventListener you prevents your instance from going out of scope and being destroyed. Read more about this by googling "as3 garbage collection" or similar. Thus you need to remove the reference to your instance.

General rule of thumb: Every time you do "addEventListener" you should make sure you have an appropriate "removeEventListener".

Basic example:

public class A
{
    public function A()
    {
        Stage.addEventListener(eventString, functionToBeTriggered);
    }

    function cleanup():void
    {
        Stage.removeEventListener(eventString, functionToBeTriggered);
    }
}

public class Foobar
{
    var a = new A();
    a.cleanup(); //by omitting this line, the instance 'a' cannot be garbage collected due to Stage holding a reference to that instance
}

Regarding your other questions:

  1. You have not disposed objA, you have only cleared ONE reference to it, but not the dependency left in addEventListener
  2. Don't understand but the answer is probably "yes"
  3. Primitive data types are not related to your issues, they are only data and can't be referenced

Upvotes: 2

Related Questions