Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Event ADDED_TO_STAGE executed more times as3

I am really curios why is this happening. I created two objects. One is child of another. I registered both with event listener ADDED_TO_STAGE. Method onAdded in classB is executed twice.

Why is this happening and how can i prevent this behaviour ?

thanx for answer

public class ClassA extends Sprite 
{
        public function ClassA () 
        {
            this.addEventListener(Event.ADDED_TO_STAGE, onAdded);
        }

        private function onAdded(e:Event):void
        {
            trace("ON ADDED 1");
            var classB : ClassB = new ClassB();
            addChild(classB);
        }
}

public class ClassB extends Sprite 
{
        public function ClassB () 
        {
            this.addEventListener(Event.ADDED_TO_STAGE, onAdded);
        }

        private function onAdded(e:Event):void
        {
            trace("ON ADDED 2");
        }
}

OUTPUT: ON ADDED 1 ON ADDED 2 ON ADDED 2

like image 262
Riddlah Avatar asked Jul 06 '13 17:07

Riddlah


1 Answers

From here: There are two similar events:

Event.ADDED_TO_STAGE
Event.ADDED

There are difference between them:

ADDED

gets dispatched when the listening DisplayObject is added to another DisplayObject (no matter if it is a Stage object or not). Also it gets dispatched if any other DisplayObject is added to the listening DisplayObject.

ADDED_TO_STAGE

gets dispatched when the listening DisplayObject is added to the stage OR to any other DisplayObject which is added to stage.


In your case it dispatches two times:

1) ClassB is added to ClassA that already added to the Stage.

2) ClassB is added to the Stage.

It's kinda low level API. You can provide custom logic in case of .parent is Stage or not. Basically ones you know that, you don't really need to listen this and you can call:

this.removeEventListener(Event.ADDED_TO_STAGE, onAdded);

to prevent calling onAdded twice.

Another way to prevent that is adding classB while constructing classA:

private classB:ClassB = new ClassB();
public function ClassA () 
{
    addChild(classB);
    this.addEventListener(Event.ADDED_TO_STAGE, onAdded);
}
like image 104
ZuzEL Avatar answered Sep 20 '22 01:09

ZuzEL