1 Object和ObjectProxy在Binding时的区别
[Bindable]public var userObject:Object=new Object(); [Bindable]public var userProxy:ObjectProxy=new ObjectProxy();
<mx:FormItem label="Object"> <s:TextInput text="@{userObject.name}"/> </mx:FormItem> <mx:FormItem label="ObjectProxy"> <s:TextInput text="@{userProxy.name}"/> </mx:FormItem>
会产生运行时warning
小结:推荐使用ObjectProxy进行绑定,以减少运行时警告。
2 自定义类的Binding
编写Account类
package org.swflash.model { public class Account { public function Account(name:String) { this.name = name; } public var name:String; } }
[Bindable]public var account:Account = new Account(); <mx:FormItem label="Account"> <s:TextInput text="@{account.name}"/> </mx:FormItem>
在项目编译时报下面警告:
在类前面使用[Bindable]标签,即可解决编译时warning
[Bindable] public class Account { ... }
如果取消[Bindable]public var account:Account = new Account();前面的[Bindable]标签,则会产生如下的编译时warning
3 双向绑定
[Bindable]public var userObject:Object={"name":"swflash"}; [Bindable]public var userProxy:ObjectProxy=new ObjectProxy({"name":"swflash"}); [Bindable]public var account:Account = new Account("swflash");
1)双向绑定代码如下:
private function userBidirectionalBinding():void{ { trace("Object.name:"+userObject.name); trace("ObjectProxy.name:"+userProxy.name); trace("Account.name:"+account.name); }
更改输入的值为swf后,控制台输出如下:
2)单向绑定实现代码如下,
private function userBinding():void{ trace("Object.name:"+userObject.name); trace("ObjectProxy.name:"+userProxy.name); trace("Account.name:"+account.name); userObject.name = objNameInput.text; proxyNameInput.name = proxyNameInput.text; account.name = accountNameInput.text; trace("Object.name:"+userObject.name); trace("ObjectProxy.name:"+userProxy.name); trace("Account.name:"+account.name); }
注意,需要取消text="@{account.name}"中的@
更改输入的值为swflasha后,控制台输出如下:
可见单向绑定在UI更改的情况下,ObjectProxy的数据感应不到更改。
小结:使用双向绑定简洁可靠,推荐使用。