2010-05-26 57 views
0

在下面的代码中,对myChild.bar()的调用会导致异常,因为myChild为空。 myParent是一个有效的对象。我不明白的是为什么myChild还没有创建。“新”适用于Flex创建周期?

我已阅读到创建对象序列相关的以下文件,但我不知道该如何“新”有关: http://livedocs.adobe.com/flex/3/html/help.html?content=layoutperformance_03.html

任何帮助表示赞赏!

// Main.mxml 

<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" creationComplete="created()"> 
    <mx:Script> 
     <![CDATA[ 
      public var myParent:Parent = new Parent(); 
      public function created():void { 
       myParent.foo(); 
      } 
     ]]> 
    </mx:Script> 
</mx:Application> 

// Parent.mxml 

<mx:Canvas xmlns:mx="http://www.adobe.com/2006/mxml" xmlns="*"> 
    <mx:Script> 
     <![CDATA[ 
      public function foo():void { 
       myChild.bar(); 
      } 
     ]]> 
    </mx:Script> 
    <Child id="myChild"/> 
</mx:Canvas> 

// Child.mxml 

<mx:Canvas xmlns:mx="http://www.adobe.com/2006/mxml"> 
    <mx:Script> 
     <![CDATA[ 
      public function bar():void { 
       trace("Hello World"); 
      } 
     ]]> 
    </mx:Script>  
</mx:Canvas> 

回答

1

creationComplete火灾对象及其所有子元素被创建并绘制到屏幕上时。由于父对象与

public var myParent:Parent = new Parent(); 

创建它不是你的主要对象的孩子,myParent前creationComplete事件触发初始化。

事实上,myParent.myChild将保持为空,直到导致myParent初始化。您可以通过将其添加到屏幕上的组件来解决此问题,或者您可以致电myParent.initialize();

0

Flex是一种可视化显示/ UI框架。它旨在保持UI项目的显示列表,并处理显示列表中项目的各种更新。

问题是您从未将您的父组件添加到显示列表中。如果您使用的是Flex 4 Spark体系结构,则使用Flex 2/3 Halo体系结构或AddElement中的AddChild方法完成此操作。

一旦使用AddChild方法将Parent组件添加到舞台中,该组件将开始逐步遍历组件lifeCycle,其中包括创建它的Children(通过createChildren()方法)以及调整和定位子组件(通过updateDisplayList( ))。当通过MXML定义组件和子项时(例如,Parent.mxml文件使用XML将Child类定义为子项),addChild方法调用在后台“自动”完成。

请记住,Flex组件LifeCycle是一个进程,可能不会立即生效。如果您对父级执行addChild;您可能无法在下一行立即访问该父母的子女。

因此,新关键字创建组件的新实例;但它不会将该组件放到displayList上供Flex Framework布局管理器处理。要纠正这种情况

的一种方式可能是这种变化的主应用程序文件:

<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" creationComplete="created()"> 
    <mx:Script> 
     <![CDATA[ 
      public function created():void { 
       myParent.foo(); 
      } 
     ]]> 
    </mx:Script> 
    <parent:Parent id="myParent" /> 
</mx:Application> 

另一种可能是这样的:

<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" creationComplete="created()"> 
    <mx:Script> 
     <![CDATA[ 
      public var myParent:Parent = new Parent(); 
      public function created():void { 
       myParent.foo(); 
      } 
      override protected function createChildren():void{ 
       super.createChildren(); 
       this.addChild(myParent); 
      } 

     ]]> 
    </mx:Script> 
</mx:Application> 

有关这个东西一些良好的阅读,通过阅读Flex组件LifeCycle文档。 http://livedocs.adobe.com/flex/3/html/ascomponents_advanced_2.html#204762

+0

谢谢,但我忘了提及我不能添加“myParent”,因为它是一个弹出窗口。有没有办法将它添加为PopUp? – deux11 2010-05-26 18:47:00

+0

PopUpManager.addPopUp(myParent,this); http://livedocs.adobe.com/flex/3/langref/mx/managers/PopUpManager.html – JeffryHouser 2010-05-26 19:30:08

+0

我的意思是问如何使用mxml标签完成。我想初始化popUp,但不能马上显示。 – deux11 2010-05-28 01:43:28