views:

37

answers:

3

I want to run some code whenever a DisplayObject is added as a child to a DisplayObjectContainer. Or to put in other words, to catch the addedToStage event of all DisplayObjects, even ones I don't know about.

Is it possible? and if not, any ideas on how to do something similar?

+1  A: 

I don't know if there is a built in way to do this.

Alternatives include the obvious,

private var _num_children:Number = 0;
addEventListener(Event.ENTER_FRAME, _checkChildren, false, 0, true);

private function _checkChildren($evt:Event):void {
    if (this.numChildren != _num_children) {
        _num_children = this.numChildren;
        // There was a child (or more) added in the last frame execution
    }
}

However, this seems like a more elegant solution...

public function _addChild($do:DisplayObject) {
    $do .addEventListener(Event.ADDED_TO_STAGE, _childAdded);
    addChild($do );
}

private function _childAdded($evt:Event) {
    // do whatever with $evt.target
}

The difference here, is the _childAdded will get fired for each and every child added via _addChild method. This means if you are doing some costly code execution you will be doing it once for each child instance.

If you use the first method, you are only calling the method once per frame, and if 10 images are added on a single frame, then it will only run once.

sberry2A
+1  A: 

Using Event.ADDED_TO_STAGE on stage Object and setting useCapture to true.

More info on event here

Example:

function onAdded(e:Event):void{
    trace(e.target.toString()); //use target to get the Object added
}
stage.addEventListener(Event.ADDED_TO_STAGE, onAdded, true); // set capture to true
Patrick
+3  A: 

An 'added' event is dispatched whenever a child display object is added to the display list via addChild() or addChildAt(). In the DisplayObjectContainer class add the listener:

addEventListener(Event.ADDED, onAdded);

and the handler:

private function onAdded(e:Event):void
{
    trace('number of children is now ' + numChildren);
}
wmid
Cheers wpjmurray :)I somehow assumed that this event fires when the object itself is added as a child of some other container. (And was to lazy to check I guess)
Leeron
Yes, it is kind of confusing using "added" as the event type since "added_to_stage" means the display object was added to stage, so "added" would imply that this display object was added to a parent display object. A better event type would have been "child_added" or something similar.
wmid