How to use two-way data binding in Flex

Problem

I want to use the new Flex  data binding.

Solution

Use the MXML Binding Tag or do it directly in your attributes.

Detailed explanation

Two-way Data Binding is a really nice new feature from Gumbo. As you know, basic Data Binding was like saying "this textfield's text attribute value always has to be this variable's content". It was really nice and could have saved lives sometimes, but it wasn't possible to do the opposite. Guess what? Now you can!

My Application

I have a simple application :

<?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/halo" minWidth="1024" minHeight="768">

  <s:layout>

    <s:VerticalLayout />

  </s:layout>

  <s:TextInput id="firstField" />

  <s:TextInput id="secondField" />

</s:Application>

Using the MXML Binding Tag

You can still use the Binding MXML tag, but if you want to use two-way binding instead of the old one, you have to set the "twoWay" attribute's value to "true" :

<?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/halo" minWidth="1024" minHeight="768">

  <s:layout>

    <s:VerticalLayout />

  </s:layout>

 

  <fx:Binding source="firstField.text" destination="secondField.text" twoWay="true" />

  <s:TextInput id="firstField" />

  <s:TextInput id="secondField" />

</s:Application>

Using the not-so-new binding syntax

With Flex 3, there was the brace syntax :

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical">
    <mx:Script>
        <![CDATA[
        [Bindable]
        protected var myVar:String;
        ]]>
    </mx:Script>
    <mx:TextInput text="{myVar}" />
</mx:Application>

The new one to use two-way Data Binding is not that different, all you have to add is a "@" symbol :

<?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/halo" minWidth="1024" minHeight="768">
  <s:layout>
    <s:VerticalLayout />
  </s:layout>
  
  <s:TextInput id="firstField" />
  <s:TextInput id="secondField" text="@{firstField.text}" />
</s:Application>

posted @ 2011-05-16 22:50  lyqandgdp  阅读(238)  评论(0编辑  收藏  举报