Flex4 AS3的簡單繫結總結

2gua發表於2013-01-03

  Flex開發中,元件的繫結功能是非常強大的,善用繫結,將大大提高開發效率。繫結實質也是事件處理,進一步說,要學好Flex,Flex的事件處理機制一定要理解透徹。接下來就對Flex AS3的簡單繫結做個總結。

  先來看看,不使用繫結時的常規處理方式:

<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 
               xmlns:s="library://ns.adobe.com/flex/spark" 
               xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600"
               fontSize="12" fontFamily="微軟雅黑">
    <fx:Declarations>
        <!-- 將非可視元素(例如服務、值物件)放在此處 -->
    </fx:Declarations>
    <s:layout>
        <s:BasicLayout />
    </s:layout>
    <s:Group top="30" left="20">
         <s:layout>
             <s:HorizontalLayout/>
         </s:layout>
        <s:TextInput id="myTextInput1"/>
        <s:Button label="複製到:" click="myTextInput2.text=myTextInput1.text"/>
        <s:TextInput id="myTextInput2"/>
    </s:Group>
</s:Application>

  效果如下:

  現在來看看使用繫結的3種場景。

  1. 元件內部繫結

<s:Group top="30" left="20">
        <s:layout>
            <s:HorizontalLayout/>
        </s:layout>
        <s:TextInput id="myTextInput1"/>
        <s:TextInput id="myTextInput2" text="{myTextInput1.text}"/>
    </s:Group>

  注意繫結使用花括號標記,效果如下,在第一個TextInput裡輸入文字,第二個TextInput自動同步顯示:

  要實現雙向同步繫結,只需這樣:

<!-- <s:TextInput id="myTextInput1"/> -->
<s:TextInput id="myTextInput1" text="{myTextInput2.text}"/>
<s:TextInput id="myTextInput2" text="{myTextInput1.text}"/>

  2. 標籤繫結

  通過標籤<fx:Binding>在元件外部進行繫結,這種方式的優點在於:由於設定在元件的外部進行,程式碼修改起來比較方便,只需集中修改就好了。

    <fx:Binding source="myTextInput1.text" 
                destination="myTextInput2.text" 
                twoWay="true"/>
    <s:Group top="30" left="20">
        <s:layout>
             <s:HorizontalLayout/>
         </s:layout>
        <s:TextInput id="myTextInput1"/>
        <s:TextInput id="myTextInput2"/> 
    </s:Group>

  從源(source)到目標(destination)繫結,twoWay屬性設定為true表示雙向同步繫結。

  效果如下:

 3. 變數繫結

  程式設計過程中將建立很多變數,這些變數也是可以跟元件繫結在一起的,這樣的話,動態生成的資料就能夠同步在對應元件裡及時重新整理顯示出來。

  可繫結變數要通過Flex的元關鍵字[Bindable]來實現。

  Flex MXML中的元關鍵字主要用途:

  • 用來描述變數、元件和類的額外屬性;
  • 宣告自定義元件所分發的自定義事件。
<fx:Script>
        <![CDATA[
            [Bindable]
            public var s:String="";
        ]]>
    </fx:Script>
    <s:Group top="30" left="20">
        <s:layout>
             <s:HorizontalLayout/>
         </s:layout>
        <s:TextInput id="myTextInput1"/>
        <s:Button label="點我" click="s=myTextInput1.text"/>
        <s:TextInput id="myText" text="{s}"/> 
    </s:Group>

  效果如下:

  總之,Flex 4在快速開發方面極具優勢,掌握好Flex,不啻於掌握了一門高效強大的開發工具,雖然現在有很多Flash、Flex的各種黑,但Flex在貢獻給Apache之後,迅速成為了Apache的頂級專案,其更新發布的速度更快了,社群支援非常活躍,在企業應用開發中,Flex能夠發揮很大作用。當然,移動應用開發能力也是很強大的,許多移動應用也是用Flash或Flex開發出來的。推薦有興趣的開發者把Flex放進你的開發工具箱裡去。

相關文章