Alain Hufkens {Rich Interactive Applications Developer}

16Jun/092

Bidirectional (two-way) data binding in Flex 4

two-wayI use data binding a lot when writing Flex applications. One of the new features in Flex 4 is bidirectional, or two-way data binding. This blog post shows you a simple example that demonstrates the difference between one-way and two-way data binding syntax.

The first example is the most commonly used data binding scenario. It uses the curly braces syntax. In the example a String variable myName binds to a TextInput field. However if you change the value in the input field, the underlying String variable is not changed. This is because this kind of data binding is only one-way. There is a way to achieve bidirectional data binding in Flex 3 and you can find more info in this article, but I will not go into detail about that in this post.

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
    <mx:String id="myName">Alain</mx:String>    
    <mx:TextInput id="nameInput" text="{myName}"/>
</mx:Application>

For example in Flex 3 the DataGrid component had two-way data binding enabled if you made it editable. In Felx 4 it has become very easy to achieve bidirectional binding. The following example is based on the same scenario as the previous one, only now the underlying String value is updated.

<?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">

    <fx:Declarations>
      <fx:String id="myName"/>
    </fx:Declarations>

    <s:layout>
        <s:VerticalLayout/>
    </s:layout>

    <s:TextInput id="nameInput" text="@{myName}"/>
    <s:SimpleText text="{myName}"/>
</s:Application>

That's basically it. The @{} syntax makes sure that the myName variable is changed and because the SimpleText label is also binded to the myName variable the value is also updated.

These are pretty simple examples, but you can find more information about the Flex 4 data binding techniques in the following articles:

Filed under: flex Leave a comment
Comments (2) Trackbacks (0)
  1. Blogged: Bidirectional (two-way) data binding in Flex 4 http://bit.ly/15AGVE (one of my favorite new features)

    This comment was originally posted on Twitter

  2. Pointers in your flex ! ;)

    But yeah, pretty cool, that should eliminate quite a bit of boilerplate code.


Leave a comment


No trackbacks yet.