11.8.使用States的延时实例工厂

11.8.1. 问题
我需要一个对象,它能为AddChild 对象实例化不同类型的对象。
11.8.2. 解决办法
创建工厂类,并赋值给AddChild 对象的targetFactory 属性。
11.8.3. 讨论
AddChild 对象的targetFactory 属性需要一个实现IDeferredInstance 接口的对象。

IDeferredInstance 接口只需要一个方法:getInstance():Object. 当AddChild 对象需要一个新的可视化对象被添加到组件时该方法返回所需的实例对象。

这里提供的类很简单,但它可根据type 属性值返回不同类型的UIComponent:
+展开
-ActionScript
package oreilly.cookbook
{
import mx.containers.HBox;
import mx.containers.VBox;
import mx.controls.Button;
import mx.controls.Text;
import mx.controls.TextInput;
import mx.core.IDeferredInstance;
import mx.core.UIComponent;
public class SpecialDeferredInstance implements
IDeferredInstance
{
private var comp:UIComponent;
private var _type:String;
public function set type(str:String):void {
_type = str;
}
public function get type():String{
return _type;
}
public function getInstance():Object
{
var text:Object;
if(_type == "TextVBox"){
comp = new VBox();
text = new Text();
text.text = "TEXT";
comp.addChild(text as Text);
var btn:Button = new Button();
btn.label = "LABEL";
comp.addChild(btn);
comp.height = 160;
comp.width = 320;
}
else
{
comp = new HBox();
text = new TextInput();
text.text = "TEXT";
comp.addChild(text as TextInput);
var btn:Button = new Button();
btn.label = "LABEL";
comp.addChild(btn);
comp.height = 160;
comp.width = 320;
}
return comp;
}
}
}

设置好targetFactory 后,AddChild 方法根据SpecialDeferredInstance 实例的type 参数可有不同类型的对象,例如:
+展开
-XML
<mx:VBox xmlns:mx="http://www.adobe.com/2006/mxmlwidth="400"
height="300currentState="empty">

<mx:Script>
<![CDATA[
import oreilly.cookbook.SpecialDeferredInstance;
[Bindable]
private var defInst:SpecialDeferredInstance =
new SpecialDeferredInstance();

]]>
</mx:Script>
<mx:states>
<mx:State name="defInst">
<mx:AddChild relativeTo="{mainHolder}"
targetFactory="{defInst}"/>

</mx:State>
<mx:State name="empty"/>
</mx:states>
<mx:Button click="currentState == 'defInst' ? currentState='empty' : currentState='defInst'label="change"/>
<mx:HBox id="mainHolder"/>
</mx:VBox>

加支付宝好友偷能量挖...


评论(0)网络
阅读(81)喜欢(0)flash/flex/fcs/AIR