[Flex]Flex的component和container的children的life cycle

作者: ldsea 分类: 程序生活 发布时间: 2008-06-09 20:10

详细大家在用Flex的时候都遇到这么一个问题,new出来的component不能直接对其内部的组件进行操作,经常会提示null的错误。当然我们自己在写Script组件的时候,可以把children的创建自己放在constructor里面。这样就不会出现这种问题。但当我们在做mxml组件的时候,这个问题就非常明显了。我们必须遵循Flex的component life cycle。通常的做法是放在property里面,例如

[code]<?xml version="1.0" encoding="utf-8"?>

<mx:Canvas xmlns:mx="http://www.adobe.com/2006/mxml" width="400" height="300">

<mx:Script>

<![CDATA[

private var title:String;

private var bNameChanged:Boolean;

public function set Title(value):void

{

if(title != value)

{

title = value;

bNameChanged = true;

this.invalidateProperties();

}

}

override protected function commitProperties():void

{

super.commitProperties();

if(bNameChanged)

{

bNameChanged = false;

lblName.text = title;

}

}

]]>

</mx:Script>

<mx:Label id="lblName" />

</mx:Canvas>[/code]

然而,你在用一些Container的时候,还是会遇到null的问题,这又是怎么回事呢?例如,你放两个上面的组件在一个TabNavigate里面。

[code]<?xml version="1.0" encoding="utf-8"?>

<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" xmlns:local="*" >

<mx:TabNavigator>

<local:TestComponent id="test1" Title="test 1" />

<local:TestComponent id="test2" Title="test 2" />

</mx:TabNavigator>

</mx:Application>[/code]
试试,保证

Error #1009: 无法访问空对象引用的属性或方法。

这个时候,我开始抱怨了,为什么Flex为什么自己不遵守自己的游戏规则,这里TabNavigator的children还没有创建就会调用,commiteProperties 或者 updateDisplayList方法。这应该是Flex的一个Bug.

现在要解决这个问题就只有让TabNavigator在创建children的时候就要把所有的children都创建。这个时候我们就要关注Container.createPolicy属性了。Container内部的children不是在createChild里面创建的,至于其children的创建时机,就好好看看

ContainerCreationPolicy,而且Container内部的children(即通过mxml加的children)和createChildren里创建的chidren可以理解为不同的类型。

在上面的例子里面的TabNavigator加上 createPolicy = “ALL”所有的文件就解决了。

如果有什么问题,请大家指正.

转自:http://www.cnblogs.com/tionase/archive/2007/04/02/696852.aspx

发表回复

您的电子邮箱地址不会被公开。