2013-10-31 18 views
0

我對以下代碼中看到的內容感到困惑。我有一個盒子容器,它有一個子按鈕(我指定的名字)。我寫了一個函數,試圖按名稱查找子按鈕。然而,這不能按預期工作 - 原因是Box有numChildren = 0出於某種原因,我期望它爲1,因爲我有一個按鈕添加到它作爲一個孩子。有人能幫助我瞭解我做錯了什麼嗎?在flex中查找後代名字的孩子

<?xml version="1.0" encoding="utf-8"?> 
<s:WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009" 
        xmlns:s="library://ns.adobe.com/flex/spark" 
        xmlns:mx="library://ns.adobe.com/flex/mx"> 
<fx:Declarations> 
    <!-- Place non-visual elements (e.g., services, value objects) here --> 
</fx:Declarations> 



<mx:Box height="100%" width="100%" initialize="initializeApp();" name="MyBox"> 
    <fx:Script> 
     <![CDATA[ 
      import mx.controls.Alert; 
      import mx.controls.Button; 
      import mx.core.FlexGlobals; 

      public function initializeApp():void { 
       var btn:Button = new Button(); 
       btn.name = "MyButton"; 
       addElement(btn); 
       btn.addEventListener(MouseEvent.CLICK, clickCallback); 
      } 

      private function clickCallback(event:MouseEvent):void{ 
       var obj:DisplayObject = findChildByName(FlexGlobals.topLevelApplication as DisplayObjectContainer, "MyButton"); 
       if (obj==null){ 
        Alert.show("Not Found"); 
       } 
       else{ 
        Alert.show("Found"); 
       } 

      } 

      private function findChildByName(parent:DisplayObjectContainer, name:String):DisplayObject{ 
       var childCount:Number = (parent==null) ? 0 : parent.numChildren; 
       for (var i:Number=0;i<childCount;i++){ 
        var child:DisplayObject = parent.getChildAt(i); 
        if (child is DisplayObjectContainer){ 
         return findChildByName(child as DisplayObjectContainer, name); 
        } 
        else{ 
         if (parent!=null && child == parent.getChildByName(name)){ 
          return child; 
         } 
        } 
       } 
       return null; 
      } 



     ]]> 

    </fx:Script> 


</mx:Box> 
</s:WindowedApplication> 

謝謝。

+0

爲什麼不只是使用'event.target'? – Cherniv

回答

0

我的猜測是,該項目可能會添加到子對象,在你的情況下它是Box,因爲,你的代碼直接在框中,指定MyBox.addElement。或FlxGobal.toplevelapp.addElement(

+0

就是這樣。非常感謝你。 – user2789284

0

findChildByName將提前返回,如果parent包含的DisplayObjectContainer。

if (child is DisplayObjectContainer){ 
    return findChildByName(child as DisplayObjectContainer, name); 
} 

這將返回找到的對象,或者爲null,如果沒有對象是在該容器中找到。

更好的是,由於Button是一個DisplayObjectContainer,因此您將嘗試深入研究它,而不檢查對象本身是否是您正在尋找的對象。

您需要檢查孩子是否是您的targ首先,在進一步挖掘之前;那麼,如果你發現孩子,只能從遞歸檢查中返回。例如:

if (parent != null && child.name == name) // Just check the name rather than getChildByName 
{ 
    return child; 
} 
if (child is DisplayObjectContainer){ 
    var foundChild:DisplayObject = findChildByName(child as DisplayObjectContainer, name); 
    if (foundChild) { 
     return foundChild; 
    } 
}