Wednesday, October 14, 2009

Two-way Data Binding in Flex 3 and 4

Two-way data binding, aka bidirectional data binding, refers to two components acting as the source object for the destination properties of each other. I.e. if you have a variable defined, and a, let say, input field with this variable bound to text property of the field, when you change the field's text the variable is changed, and when you change the variable, the field's text property is changed. In Flex 3 this is possible using a combination of curly braces and <mx:binding/> statement.Below is the simple example illustrating this:
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="" layout="absolute" minWidth="1024" minHeight="768">
 <mx:String id="myName"/>
 <mx:Binding source="nameInput.text" destination="myName" />
 <mx:TextInput id="nameInput" x="30" y="28"/>
 <mx:Label x="31" y="68" text="{myName}"/>
In Flex 4 this can be archived much easier, inline using declaration: @{bindable_property}.Code example:
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="" 
  xmlns:mx="library://" minWidth="1024" minHeight="768">
  <fx:String id="myName"/>
 <s:VGroup width="200" height="67" x="37" y="38">
  <s:TextInput id="nameInput" text="@{myName}"/>
  <mx:Spacer height="10"/>
  <s:SimpleText text="{myName}"/>