Archive for October, 2008

Data Binding Gone Wild!

Posted in Adobe Flex, Flex, Uncategorized with tags , , , , , on October 29, 2008 by devgirl

The ability to base a property of an object off a dynamically changing value is a benefit of data binding that is often unknown or overlooked by Flex developers. However it is an extremely valuable feature and can save a lot of time coding and handling various events, not to mention much cleaner code! This is particularly true for those properties requiring a boolean, such as ‘enabled’ or ‘visible’. The toggle can be done during execution based on a certain sequence of events. The code returning the value for the property can be included within the binding brackets in the case where minimal code is needed to derive the value, or via a function call that returns the value. The following code excerpt shows how this can easily be done in your Flex application. It basically sets the ‘enable’ property of the Delete button to a dynamically derived value that indicates whether a row in the grid has been clicked. Simple as that!

<?xml version="1.0" encoding="utf-8"?>
<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
	<mx:Script>
		<![CDATA[
			import mx.collections.ArrayCollection;

			private var employeeCollection:ArrayCollection = new ArrayCollection([
				{id:1, firstname:"Tom",lastname:"Taylor", position:"VP Sales"},
	                        {id:2, firstname:"John",lastname:"Jones", position:"Operations"},
	                        {id:3, firstname:"Margaret",lastname:"Miller", position:"VP Marketing"},
	                        {id:4, firstname:"Sarah",lastname:"Sanders", position:"VP Finance"},
	                        {id:5, firstname:"Ron",lastname:"Roberts", position:"Product Manager"},

			]);
			private function onDeleteBtnClick(event:MouseEvent):void
			{
				employeeCollection.removeItemAt(emplDataGrid.selectedIndex);
			}
		]]>
	</mx:Script>

	<mx:VBox left="10" top="5" width="480">
		<mx:DataGrid id="emplDataGrid" dataProvider="{employeeCollection}" width="480">
			<mx:columns>
				<mx:DataGridColumn dataField="id" headerText="Employee ID"/>
				<mx:DataGridColumn dataField="firstname" headerText="First Name"/>
				<mx:DataGridColumn dataField="lastname" headerText="Last Name"/>
				<mx:DataGridColumn dataField="position" headerText="Position"/>
			</mx:columns>
		</mx:DataGrid>
		<mx:Button id="deleteBtn" left="10" label="Delete Employee" 
			click="onDeleteBtnClick(event)" 
			enabled="{emplDataGrid.selectedIndex > -1}"/>
	</mx:VBox>
</mx:WindowedApplication>

Comments welcome 🙂

Advertisements