Tuesday, May 10, 2011

Why Flex? Examples

In the last post, we just have a feel of why flex is. In this post I would like to support each point we discussed in the last post with examples.

First let us go with programming model of the flex. Flex supports component based programming model as we discussed earlier.
I just want to create a component which can be reused in many applications. Let us start with a simple Hello World component and use it in another application as a component.

Here is the Main.mxml (Which is a application includes HelloWorld.mxml component.

<?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/mx" minWidth="955" minHeight="600" xmlns:examples="flex.examples.*">
<fx:Declarations>
<!-- Place non-visual elements (e.g., services, value objects) here -->
</fx:Declarations>
<examples:HelloWorld id="helloWorld"  width="100%" height="100%"/>
</s:Application>


Here is the HelloWorld.mxml component.

<?xml version="1.0" encoding="utf-8"?>
<s:BorderContainer xmlns:fx="http://ns.adobe.com/mxml/2009"
   xmlns:s="library://ns.adobe.com/flex/spark"
   xmlns:mx="library://ns.adobe.com/flex/mx" width="400" height="300">
<fx:Script>
<![CDATA[
import mx.collections.ArrayList;
import mx.controls.Alert;

import spark.events.IndexChangeEvent;
[Bindable]
private var list:ArrayList = new ArrayList([{label:"Flash"},{label:"Flex"},{label:"AIR"}, {label:"Adobe"}]);

protected function dropdownlist1_changeHandler(event:IndexChangeEvent):void
{
// TODO Auto-generated method stub
Alert.show("Hello, Welcome to the world of "+combo.selectedItem.label,"Message");
combo.selectedIndex = -1;
}

]]>
</fx:Script>
<fx:Declarations>
<!-- Place non-visual elements (e.g., services, value objects) here -->
</fx:Declarations>
<s:DropDownList id="combo" x="171" y="118" dataProvider="{list}" change="dropdownlist1_changeHandler(event)">
</s:DropDownList>
<s:Label x="126" y="123" text="Select" height="15"/>
</s:BorderContainer>

In flex, xmlns tag is used to shorten the package where the component is placed and last part of the package is used as a tag for that component to include in other component or application.

If you observe from the code it is clear that HelloWorld.mxml and Main.mxml are two different components. But I used HelloWorld.mxml inside Main.mxml (Main.mxml is composed from HelloWorld.mxml). This is just a simple example. You can do lot more things with flex components. Check the output of the above code from the below picture.  Selecting one of the items (Flash, Flex, AIR, Adobe) from the list will alert you with the message.




1 comment: