Flex 4 数据绑定

 

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

 

 

 写道
warning: unable to bind to property 'name' on class 'Object' (class is not an IEventDispatcher)
 

 

 

小结:推荐使用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>

 

 在项目编译时报下面警告:

 

 

 写道
Data binding will not be able to detect assignments to "name".
 

 

 

在类前面使用[Bindable]标签,即可解决编译时warning

 

[Bindable]
public class Account
{
    ...
}
 

 

如果取消[Bindable]public var account:Account = new Account();前面的[Bindable]标签,则会产生如下的编译时warning

 

 写道
Data binding will not be able to detect assignments to "account".
 

 

 

 

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后,控制台输出如下:

 

 写道
Object.name:swf
ObjectProxy.name:swf
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后,控制台输出如下:

 

 写道
Object.name:swflasha
ObjectProxy.name:swflash
Account.name:swflasha
Object.name:swflasha
ObjectProxy.name:swflash
Account.name:swflasha
 

 

可见单向绑定在UI更改的情况下,ObjectProxy的数据感应不到更改。

 

小结:使用双向绑定简洁可靠,推荐使用。

 

你可能感兴趣的:(UI,Flex)