0
votes

I have two mxml files in a flex project: But when I trace a.cBtn, it is null. Why should it be?

test.mxml :

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="runIt()">
<mx:Script>
 <![CDATA[
  public function runIt():void
  {
   var a:abc = new abc();
   trace(a.cBtn);//a.cBtn is null here
  }
 ]]>
</mx:Script> 
</mx:Application>

And, abc.mxml :

<?xml version="1.0" encoding="utf-8"?>
<mx:Canvas xmlns:mx="http://www.adobe.com/2006/mxml" width="400" height="300">
 <mx:Button x="108" y="73" label="Button" id="cBtn"/>

</mx:Canvas>
2

2 Answers

0
votes

The underlying issue here is that in Flex, the children components of a given flex container component are not created until that container is initialized. The initialization process starts after you add the container to the display list. As noted above, the CREATION_COMPLETE event is fired after initialization is done and the children are instantiated, so you can safely access children at that point.

It's pretty ugly, but if you absolutely need to access the children of a component before you want to add that component to the display list, you can call "initialize()" on your container.

public function runIt():void
{
    var a:abc = new abc();
    trace(a.cBtn);//a.cBtn is null here
    a.initialize();
    trace(a.cBtn);//a.cBtn is not null here
}
0
votes

You need to wait for the creationcomplete event.

public function runIt():void 
{ 
    var a:abc = new abc(); 
    a.addEventListener(FlexEvent.CREATION_COMPLETE, traceIt)
    trace(a.cBtn);//a.cBtn is null here 
} 
private function traceIt(e:Event):void
{
    trace(a(e.target).cBtn)
}