Home > Flex > Making the most out of Data Binding


Making the most out of Data Binding

September 10th, 2007

Data Binding is a great way to reduce unnecessary marshaling and marshaling code when manipulating data based on user input. Read on for some neat tips.

1) Alway use custom Bindable Value Objects. For a small project you can get by with using mx:Model but if you intend to access your data from more than one view a ValueObject is a must.

package
{
	[Bindable]
	public class MyValueObject
	{
		public var boolean1:Boolean;
		public var boolean2:Boolean;
		public var boolean3:Boolean;
		public var string1:String;
		public var string2:String;
		public var selector1:String;
		public var selector2:String;
	}
}

2) Define your ValueObjects from MXML to ease binding. Use one object for input data and bind input fields to it. Use a second object for output data and bind it to the input fields.

Input Data:

<local:MyValueObject id="inputData"
	boolean1="true"
	boolean2="true"
	boolean3="true"/>

<mx:CheckBox id="cb1" label="CheckBox 1"
	selected="{inputData.boolean1}"/>
<mx:CheckBox id="cb2" label="CheckBox 2"
	selected="{inputData.boolean2}"/>
<mx:CheckBox id="cb3" label="CheckBox 3"
	selected="{inputData.boolean3}"/>

Output Data:

<local:MyValueObject id="outputData"
	boolean1="{cb1.selected}"
	boolean2="{cb2.selected}"
	boolean3="{cb3.selected}"/>

3) When dealing with input components on un-initialized tabs, instead of setting creationPolicy=all you can just add some error checking into your Data Binding tags:

<local:MyValueObject id="outputData"
selector1="{(rb1!=null)?rbg1.selectedValue:inputData.selector1}">

4) If you are working with ComboBoxes or other input components where you need to translate the value stored in your ValueObject into an index or different value for the component to read, you can bind to functions also:

<local:MyValueObject id="outputData"
selector2="{(menu1!=null)?indexToValue(menu1.selectedIndex):
inputData.selector2}"/>

<mx:Script>
    <![CDATA[
	private function valueToIndex(value:String):Number
	{
		switch (value)
		{
			case 'opt1': return 0;
			case 'opt2': return 1;
			default: return 2;
		}
	}
	private function indexToValue(index:Number):String
	{
		switch (index)
		{
			case 0: return 'opt1';
			case 1: return 'opt2';
			default: return 'opt3';
		}
	}
    ]]>
</mx:Script>

<mx:ComboBox id="menu1"
	selectedIndex="{valueToIndex(inputData.selector2)}">
	...
</mx:ComboBox>


Download the Source



Christopher Flex

  1. No comments yet.
  1. No trackbacks yet.
You must be logged in to post a comment.