Flex 3:如何访问组件的孙子

时间:2010-10-21 18:15:07

标签: flex grandchild

我需要访问topBox的孙子,并确定它们是否是按钮。

下面的这个功能(谢谢Flextras.com)抓住了topBox的直接孩子,这些孩子就是HBox。我如何进入topBox的孙子级别?或者唯一的方法是在每个HBox上运行此功能吗?

for (var i : int =0; i<topBox.numChildren; i++){
  var child : DisplayObject = topBox.getChildAt(i);
  var myButton:UIComponent = child as UIComponent;
    blah blah               
} 


<mx:VBox id="topBox">

    <mx:HBox id="Hbox1">
        <mx:Button id="button1"
            label="button1" 
            click="myClickHandler"/>

        <mx:Button id="button2" 
            label="button2" 
           click="myClickHandler"/>
    </mx:HBox>

   <mx:HBox id="Hbox2">
        <mx:Button id="button3"
            label="button3" 
            click="myClickHandler"/>

        <mx:Button id="button4" 
            label="button4" 
           click="myClickHandler"/>
    </mx:HBox>

<mx:VBox>

1 个答案:

答案 0 :(得分:2)

//declare child access function
private function processChildren(target:DisplayObjectContainer, handler:Function):void
{
    for (var i:int = target.numChildren - 1; i >= 0; i--)
    {
        handler(target.getChildAt(i));
    }
}

//call it with handler as anonymous function (may be plain one as well)
processChildren(topBox, function(target:DisplayObjectContainer):void
   {
       processChildren(target, function(target:DisplayObjectContainer):void
       {
           //this will be called on grandchildren
           if (target is Button)
           {
               //do something
           }
       });
   });

为了让它看起来不那么令人生畏,可以用普通函数替换匿名函数,但这个想法应该是明确的。