2013-10-31 15 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; 
    } 
}