开发者

Is there a way for listening for changes in flash.display.DisplayObjectContainer numChildren property?

开发者 https://www.devze.com 2022-12-20 02:44 出处:网络
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, eve开发者_开发技巧n o

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, eve开发者_开发技巧n ones I don't know about.

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


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);
}


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消