2008年6月27日 星期五

Flex 技巧 - 将资料绑定封装起来

Ticore's Blog

之前介绍了 纯手工设置 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 - 纯手工设置 DataBinding 的方式
Flex 技巧 - BindingManager 使用方式
Flex 技巧 - 观察 Data Binding 资料变化
Flex Tip - 在 Data Binding 内使用 [...] 运算子
Flex 2 Bindable Metadata Tag 背后实际作用
Flex 2.0 - 以 ActionScript 3.0 动态设置 Data Binding

转载请注明出处 http://ticore.blogspot.com/2008/06/flex-tip-encapsulate-databinding.html

2 意见 :

warmwater 提到...

谢谢分享这技巧

有个问题想请问一下,在BindingComp.mxml里面您使用了Main01这个type,请问01这个数字是怎么来的??不能直接用Main当Type吗?

卸卸

{id: "Ticore"}; // 提到...

谢谢告知,贴上来的时候,没有改到~~
因为自己测试习惯用 Main01, Main02... 编号