2010-10-21 45 views
0

我需要訪問topBox的孫子們,並確定它們是否是按鈕。Flex 3:如何訪問組件的孫子們

下面的這個函數(謝謝你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

你知道如何獲取組件的孩子。你爲什麼問如何讓孩子的孩子? – alxx 2010-10-21 18:59:06

+1

爲什麼你需要照顧孫子女?一個組件應該只關心自己的孩子。 – DyreSchlock 2010-10-21 19:09:53

回答

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

,使它看起來那麼嚇人,可以用普通的人代替匿名函數,但這個想法應該是清楚的。

+0

嗨alxx,非常感謝您的幫助。 – Laxmidi 2010-10-21 20:00:49