之前介紹了 純手工設定 Flex DataBinding 的方式
不過那挺麻煩的
假如想要將 DataBinding 封裝起來,保留部分彈性
又不想要那麼麻煩的設定方式
不妨可以試試看以下的方式
在這個例子中,完全的將 DataBinding 封裝在一個 MXML Component 中
必須要指定好目標物,Component 內的 DataBinding 才會發生作用
想要停止 DataBinding 也很簡單,只要將目標屬性設為 null 就好
甚至可以對一份資料,準備多個 DataBinding Component
只要在執行期動態替換 Component,就能達到切換 DataBinding 行為的目的
其實還挺方便的
Main.mxml:
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
verticalAlign="middle" backgroundColor="#FFFFFF"
creationComplete="init();" fontSize="12">
<mx:Script>
<![CDATA[
public var comp:BindingComp;
public function init():void{
comp = new BindingComp();
comp.initialize();
}
]]>
</mx:Script>
<mx:HBox>
<mx:Label text="No 1:" />
<mx:NumericStepper id="no1" maximum="100" />
</mx:HBox>
<mx:HBox>
<mx:Label text="No 2:" />
<mx:NumericStepper id="no2" maximum="100" />
</mx:HBox>
<mx:CheckBox id="chk" label="DataBinding Enabled"
change="comp.target = chk.selected ? this : null;" />
</mx:Application>
<!-- Ticore's Blog - http://ticore.blogspot.com/ -->
BindingComp.mxml:
<?xml version="1.0" encoding="utf-8"?>
<mx:UIComponent xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script>
<![CDATA[
[Bindable]
public var target:Main;
public function doBinding1(... args:*):void{
if (target) target.no2.value = target.no1.value;
}
public function doBinding2(... args:*):void{
if (target) target.no1.value = target.no2.value;
}
]]>
</mx:Script>
<mx:Model>
{doBinding1(target.no1.value)}
</mx:Model>
<mx:Model>
{doBinding2(target.no2.value)}
</mx:Model>
</mx:UIComponent>
<!-- Ticore's Blog - http://ticore.blogspot.com/ -->
線上測試範例:
相關連結:
Flex 4 Gumbo 雙向資料繫結測試
Flex - 純手工設定 DataBinding 的方式
Flex 技巧 - BindingManager 使用方式
Flex 技巧 - 觀察 Data Binding 資料變化
Flex Tip - 在 Data Binding 內使用 [...] 運算子
Flex 2 Bindable Metadata Tag 背後實際作用
Flex 2.0 - 以 ActionScript 3.0 動態設置 Data Binding




