flex 属性绑定

as3支持绑定变量,控件的属性,函数,我们这里要讨论的是用as来动态绑定。

1.使用{}实现绑定:
[Bindable]
private var ac:ArrayCollection = new ArrayCollection();
<s:ComboBox dataProvider="{ac}" />
2.使用Binding标签实现绑定:
<mx:Binding source="ti1.text" destination="ti2.text" />
<mx:TextInput id="ti1" />
<mx:TextInput id="ti2" />
 
3.函数做绑定源:
private function bindFunction(val:String):String{
return "绑定的值为:" + val;
}
<s:TextInput id="t1"/>
<s:TextInput id="t2" text="{bindFunction(t1.text)}"/>
 
4.用as实现绑定:
有些组件是用as生成的,这时就没法用标签绑定了,解决办法是用as绑定。
private var t1:TextInput;
private var t2:TextInput;
private var watcher:ChangeWatcher;
 
private function init():void{
t1 = new TextInput();
vg.addElement(t1);
t2 = new TextInput();
vg.addElement(t2);
watcher = BindingUtils.bindProperty(t2,"text",t1,"text");
}
private function onClick(event:MouseEvent):void{
if(watcher.isWatching()){
watcher.unwatch();
Alert.show("取消绑定");
}else{
watcher.reset(t1);
Alert.show("重新绑定");
}
}
 
5.自定义绑定事件:
[Bindable(event="userNameChanged")]
private var userName:String;
 
private function onClick(event:MouseEvent):void{
userName = t1.text;
if(userName != "111"){
dispatchEvent(new Event("userNameChanged"));
}
}
<s:TextInput id="t1" />
<s:TextInput id="t2" text="{userName}"/>
<s:Button label="click" click="onClick(event)" />
将变量userName与t2的text属性绑定,当变量改变时,不一定就发生绑定(如输入111),只有当调用dispatchEvent方法发送事件时才发生绑定。
 
6.使用对象做绑定源:
直接在对象前加[Bindable]是不行的,以为这样的话,改对象的属性更新时目标是不会更新的,解决这个问题,有两种方法:
6.1.对象的每个需要绑定的属性前面都加上[Bindable]标签
6.2.使用ObjectProxy:
[Bindable]
private var objProxy:ObjectProxy;
private var user:User;
private function init():void{
user = new User();
user.id = 1;
user.name = "name1";
objProxy = new ObjectProxy(user);
}
private function onClick(event:MouseEvent):void{
objProxy.id = 2;
objProxy.name = "name2";
}
<s:TextInput id="t1" text="{objProxy.id}" />
<s:TextInput id="t2" text="{objProxy.name}"/>
<s:Button label="click" click="onClick(event)" />

你可能感兴趣的:(Flex)