Search Flex Components Free

Custom Search
Showing posts with label Flex. Show all posts
Showing posts with label Flex. Show all posts

March 11, 2010

What is Flex?

Flex is a convoluted term for sure. As the history of the product has evolved it has been a j2ee server, an as framework, a compiler and and IDE among other things.

In todays day and age we are at a released version 3, with version 4 in beta. The term flex typically refers to a way of developing flash platform application using the components in the open source framework developed by adobe.

Flex applications are written as a combination of xml markup (mxml) and actionscript much in the same vein that html applications are written with JS. The big difference is that the output of all your mxml and actionscript files is a single swf that can be embedded in a web page and displayed to the world. You can also use Flex to develop AIR applications, applications that can be installed on a users desktop.

Although Adobe produces an IDE to help in developing Flex applications it is not a requirement. Everything

Flex 3 Tutorials

With Web users expecting richer and more complex interfaces, Rich Internet Applications (RIAs) are seeing a huge increase in popularity. Adobe Flex is the tool of choice for many web developers when it comes to building RIAs.

Flex used to be one of those technologies that was only used by large corporate organisations -- the first release of Flex was priced at around US$15,000 per CPU (a tad expensive for most developers) Since then, Flex has been released as open source software. Talk about a complete turnaround!

Flex is now in version 3.0, and runs on the Adobe Flash Player 9 runtime. Flex 3.0 has been such a success that Flex 4.0 has been announced for release in 2009. As a developer, getting in early and learning all you can now is a good idea -- standing out in the Flex community will soon become extremely difficult.

Developers are picking up Flex with great speed. One of the reasons for this is that Flex programming is relatively easy to learn if you're already familiar with XHTML. Of course, there's always a transition period when you're getting used to a new environment, but learning Flex won't take long!

Another drawcard is that Flex applications can be developed to run on a user's desktop thanks to the wonders of the Adobe AIR (Adobe Integrated Runtime) platform. Now you can develop and launch an RIA that runs in a web browser and as a desktop application. Deploying an application to a user's desktop with Adobe AIR is easy -- all that users need to do is click a link in the web browser to install the AIR runtime and your RIA on their machine. Now that's quick deployment!
he first thing you'll notice is that MXML is an XML format. To indicate to the Flex compiler that we're defining an application, we use the element, in the same way we use the tags to define a web page. We can then add other elements within the tag. In the above example, we've added a tag to create a button, just as we'd use an tag in a web page form.

As you can see, this is all very similar to constructing a traditional web page, and the framework provides you with everything you might use in XHTML (buttons, lists, etc.) and more. All you have to learn is the properties, methods and the names of the components in the framework, all of which are available from the Adobe Flex 3 language reference.

Why Use Flex?

If you're considering building a RIA, you have a few choices of technology, including Flex, Ajax, and Microsoft Silverlight. If you look at these options objectively, the development effort required for each (and the resulting user experience) is roughly the same. One of the benefits of Flex is its reach -- the Adobe Flash Player, upon which Flex applications run, is already installed on about a billion computers wordwide!

Of course, Ajax also uses technologies that are installed on almost every computer in the world -- JavaScript, XHTML, and CSS. One of the downfalls of Ajax, however, is that cross-browser compatibility can be difficult to achieve. What might work in one browser (for example, Firefox) might not work in another (such as Internet Explorer), so the debugging process has the potential to become difficult and long-winded.

Microsoft Silverlight, on the other hand, is similar to Flex in that it runs on a browser plugin. Silverlight, however, has yet to reach the installed userbase of the Flash player.

If you're just starting out with building RIAs, you should definitely try all of them to see which one you like best and find easiest to work with -- each of Flex, Silverlight and Ajax has its advantages and disadvantages. In my opinion, though, Flex is definitely the best RIA development technology available. Additionally, if you're a fan of the Adobe Creative Suite, it's good to know that many of these tools (Flash, Photoshop, Illustrator, Fireworks and so on) have Flex component integration built into them, which is a bonus no matter how you look at it.

Overview of the Flex Framework

A lot of people steer clear of the Flex framework because they think it's complicated. But generally speaking, a framework is just a set of reusable classes that can work together to provide a base for an application.

Take a house as an analogy: every house on the planet has a framework. Each house has a foundation and walls, and those walls can't stand without the foundation. Once the foundation has been laid and the walls are up, a roof can be applied and the interior designed and implemented, while work continues on the initial foundation.

If we apply this analogy to the Flex framework, we have a stack of logic -- the controller logic -- that has been made available for communicating with a database, handling security, writing to the file system, and so on. There are also the user interface elements -- buttons, canvases, dropdown lists, and so on. All of these also form the foundation of your Flex application -- the concrete slab, the timber beams and the bricks with which to build your house.

Flex is easy for web developers to learn because, at its core, it has a lot in common with (X)HTML, CSS, and JavaScript. Suppose you wanted to create a simple web page with a form button. In XHTML you'd type the following:





Button Example







When you view this markup in a web browser, you'll see a button displayed with the label "This is a button".

The XHTML button

To display something similar in Flex we use a form of markup called MXML. Here's the MXML markup for our previous example:


layout="absolute">
id="newButton"
click="checkForm()"/>

January 1, 2008

Installing the latest nightly Flex 3 SDK build into Flex Builder 3

Continuing my post from the the other day, if you’re trying out Flex 3 SDK and Flex Builder 3 (codename: Moxie), you may want to consider downloading and installing a newer nightly build of the SDK so you can take advantage of all the bug fixes that happen on a daily basis. The first step is to grab the latest version of the SDK, which can be found over on the Adobe Labs site at http://labs.adobe.com/technologies/flex/sdk/flex3sdk.html. All you need to do is read the terms of use and check the check box to enable the downloads. That’s it, no logging in, or registering, just one click and go!
Currently you have a few different options of things to download:
You can download the beta 1 build of the Flex 3 SDK (67 MB ZIP, released June 11, 2007), which includes support for building Adobe AIR (codename: Apollo) applications (for more information, check out the
Adobe Integrated Runtime (AIR) page on Adobe Labs). According to the “Flex 3 Planning” page on the official Adobe Flex Wiki (see http://flexwiki.adobe.com/confluence/display/ADOBE/Flex+3+Planning), You can expect to see Beta 2 ”Feature Complete” some time in late July/early August, with Flex 3 shipping in Q4, 2007 (yay!)


Flex 3 milestone schedule:
Date
Target
April 9, 2007
M1 Release (Alpha)
June 11, 2007
M2 Release (Beta 1)
October 2007 (was: late July/early August)
M3 Release (Beta 2) - Feature Complete
Late 2007 (was: late August/early September)
M4 - Release Candidate
Early 2008 (was: Q4 2007)
Final Release
OK, back on topic… After reading and agreeing to the terms of use, click the check box on the Flex 3 SDK page on Labs (
http://labs.adobe.com/technologies/flex/sdk/flex3sdk.html) to download a copy of the Flex SDK. Here you have a few different choices. You can download any/all of the following:
“Flex 3 SDK Beta 1″ (which includes support for Adobe AIR).
“Flex 3 Beta 1 Compiler Modules”. These include compiler ISAPI filters for Windows, as well as compiler modules for Apache on Windows, Macintosh, and Linux.
“Recent Nightly Builds of the Flex 3 SDK” (Note: “The nightly builds of the Flex 3 SDK do not include support for Adobe AIR. If you require Adobe AIR support you should use the beta 1 version of the Flex 3 SDK.”).
With that out of the way, I’ll assume you already have Flex Builder 3 installed, so grab the most recent copy of the nightly build and download the ZIP file to your desktop (or somewhere easily accessible). If you’re so inclined, you can read the changelist to see which bugs have been fixed in this release. Just click on the “View” link in the Changes column and it should pop up a new browser window.
With the download complete, locate the flex_sdk_3.zip file, and expand it. You should see about 8 directories, as well as an XML file, a license.htm file and readme.htm. According to the readme.htm file (which may not be updated for Flex 3 yet), the Flex SDK contains the following directories:
asdoc - Contains ASDoc related files. ASDoc is a command-line tool that is you can use to create HTML documentation from theclasses in your Flex application.
bin -Contains command-line tools such as mxmlc, compc, asdoc and fdb. You use these tools to compile, debug and document Flex applications and components.The bin/jvm.config file contains Java VM settings.
frameworks - Contains the framework.swc file, frameworks.swc source code, and other helper files that you use to compile Flex applications.The frameworks/flex-config.xml file includes the default compiler options.
lib - Contains JAR files used by the compilers.
runtimes - Contains debugger versions of Adobe® Flash® Player 9 for Linux, Macintosh, and Windows.
samples - Contains source code for sample applications.
templates - Contains HTML templates for Flash Player detection and history management.
With the ZIP file expanded on your harddrive, create a new folder on your harddrive. I chose “C:\dev\FlexSDK” since it is easy to find and a minimal number of letters to type. Copy each of the files and folders you just unzipped into aforementioned folder. So now you should have a folder like “C:\dev\FlexSDK\runtimes\” (where you can find the various Adobe Flash Players).
Next, start up your copy of the Flex Builder 3 beta. If you’ve made it this far and still don’t have that installed, download it from this handy URL:
http://labs.adobe.com/technologies/flex/flexbuilder3/ (In a later post I’ll walk through installing the standalone version of Flex Builder now, so sit tight if you’re lost).
After Flex Builder 3 has launched, I’ve found two painless ways to add our newly downloaded SDK:
Method 1) From the main menu, select Window > Preferences to open the Preferences dialog box. Expand the “Flex” tree, and select the “Installed Flex SDKs” option. This brings up a data grid of all currently installed Flex SDKs and their locations. It also allows you to check off which SDK you want to set as the default SDK by clicking the check box on the left of the SDK name. To add a new SDK, click the “Add” button to launch the “Add Flex SDK” dialog box. This dialog box allows you to browse for a new SDK directory, as well as give it a name. In my case, I’m going to set the Flex SDK directory to “C:\dev\FlexSDK” and give it a name of “Flex SDK (Latest)” and click OK. It’s important to note that you’re adding an additional SDK here. You aren’t overwriting anything, or replacing anything. You still have the option to compile your MXML files with the previous versions of the SDKs, such as Flex 2.0.1 Hotfix 2, or Flex Moxie M2, both of which came installed with Flex Builder 3 Beta 1. After clicking OK, you return to the Installed Flex SDKs page. From here, click the check box next to “Flex SDK (Latest)”, or whatever name you used, to set it as the default SDK. This allows you to compile against the latest version of the SDK by default, yet still have the ability to compile against Flex 2.0.1 or Flex 3 SDK Beta 1 within a few clicks. You could also download a nightly build and extract it to a nested folder within your C:\dev\FlexSDK folder. For example, I could have created C:\dev\FlexSDK\build_177055 and then add each nightly build of the SDK to Flex Builder. While this may be overkill for most, it allows you to easily revert back to previous versions of the SDK if something was working in a previous build but not in newer builds.
Method 2) Right-click a project folder in Flex Builder’s Navigator tab and select Properties to open the Properties for dialog box. From here, click the Flex Compiler option on the left to see the various Flex SDKs currently configured by Flex Builder. Here, you can set the SDK that the project will compile against, or override the default SDK with a specific one (such as Flex 2.0.1 Hotfix 2, or any other installed SDK). To add a new Flex SDK from this screen, click the “Configure Flex SDKs…” link on the right to be taken back to the Preferences dialog discussed above.
That’s it. Downloading and installing new SDKs into Flex Builder is a pretty simple and straight forward process.

December 27, 2007

Flex Developer Certification

An Adobe Certified Expert (ACE) has earned a certification created specifically for graphic designers, Web designers, video professionals, system integrators,value-added resellers, developers, or business professionals seeking recognition for their expertise with Adobe products.

Levels:

  • Single product certification: Recognizes your proficiency in a single Adobe product.
  • Specialist certif cation: Recognizes your proficiency in a specific medium:Print, Web or Video. To become certified as a Specialist, you must pass the exams on the required products listed below.
  • Master certification: Recognizes your skills in terms of how they align with the Adobe product suites. To become certified as a Master, you must pass the exam for each of the products in the suite.

Registration:

Cost:

Each exam is US$150 or local currency equivalent.

How to prepare for an exam:

ACE exams are computer-delivered, closed-book tests consisting of 60 to 90 multiple-choice questions. Each exam takes one to two hours to complete, and results are given to you at the testing center immediately after you finish.Adobe recertification exams are Web administered exams that are available to current ACEs only. The exams are delivered to your desktop via the Web. The tests consist of 30-60 multiple choice questions. Each exam takes approximately 30 to 60 minutes to complete. Results are revealed immediately online after you finish.

Following is a detailed outline of the information covered on the ACE Exam.

1. Flex Application User Interface (UI) Creation

  • Identify and describe the basic UI controls used in a Flex application.
  • Identify the purpose of UI containers and when to use them.
  • Identify how to change the look and feel of a design by using API styles and style sheets.
  • Recognize how to customize changes, control-related presentation layouts and navigation in an application by using view states, and using transitions and eff ects.

2. Flex System Architecture and Design:

  • Recognize how UML and Use Cases are used in object-oriented design.
  • Identify the relationship of design patterns with respect to system architecture.
  • Recognize and describe event-based programming model in events.
  • Identify how to build loosely-coupled components.
  • Recognize how Inheritance, Encapsulation, and Polymorphism works.
  • Recognize the structure of a J2EE architecture.

3. Flex Application Programming Fundamentals

  • Identify the properties and relationships between classes and objects and how they work in flex.
  • Identify how to display data in Flex.
  • Identify how to manipulate data in Flex.
  • Recognize how to validate data by using built-in and custom validator classes.
  • Recognize how to create and use ActionScript classes.
  • Identify the purpose and uses of handling events in Flex.
  • Recognize how to use XML data in Flex.
  • Recognize how to create and use custom components in Flex.
  • Recognize how to display data using diff erent chart types, formats, and legends.

4. Interacting with Remote Data and Flex Applications

  • Recognize how to use Remote Procedure Call (RPC) services.
  • Recognize how to manage data using Flex Data Services (FDS).

Sample questions :

1. Identify the purpose of UI containers and when to use them.Which two UI containers support absolute layout positioning? (Choose two.)

  • Tile
  • Grid
  • VBox
  • Canvas
  • Application

Correct Answer: D, E

2. Identify how to change the look and feel of a design by using API styles and style sheets.Your application includes the following declaration:
<mx:Style>.largeFont { fontSize: 15 }</mx:Style>

You want to assign a visual control to be a member of the myFontStyle class.Which syntax should you use?

  • class=”myFontStyle”
  • class=”.myFontStyle”
  • styleName=”myFontStyle”
  • styleName=”.myFontStyle”

Correct Answer: C

3. Identify how to change the look and feel of a design by using API styles and style sheets.Which statement about Cascading Style Sheet properties in Flex is true?

  • Spaces are allowed in property names
  • All CSS properties are available in Flex
  • Components CANNOT by styled using CSS
  • Class selectors can be applied to a component using the styleNameproperty

Correct Answer: D

4. Recognize how to customize changes, control-related presentation layouts and navigation in an application by using view states, and using transitions and effects.Which kind of data should be passed to the targets property of an effect?

  • Array
  • Object
  • Control
  • Container

Correct Answer: A

5. Identify how to build loosely-coupled components.Which statement about loosely-coupled components is true?

  • They decrease reusability
  • An event model CANNOT be used
  • Data can be sent by binding variables to component attributes
  • They have direct knowledge of the properties and methods of other components

Correct Answer: C

6. Recognize how Inheritance, Encapsulation, and Polymorphism works You have a custom ActionScript class named MyClass that implements an interface named MyInterface. You want to create an instance of the class, and be able to pass it to a method that accepts any class that implements the interface.Which syntax should you use?

  • var obj:MyClass = new MyInterface();
  • var obj:MyInterface = new MyClass();
  • var obj:MyClass = new MyClass() as MyInterface;
  • var obj:MyInterface = new MyInterface(new MyClass());

Correct Answer: B

7. Recognize how to create and use ActionScript classes.You have created a custom ActionScript class called MyClass. You want to be able to pass in an optional argument that is typed as an Object.Which is the correct signature of the constructor method?

  • public function MyClass(item:Object)
  • public function MyClass(item:Object = null)
  • public function MyClass(item:Object):MyClass
  • public function MyClass(item:Object) as MyClass

Correct Answer: B

8. Recognize how to display data using diff erent chart types, formats, and legends.Which type of variable should be passed to the series property of a charting component?

  • Data Transfer Object
  • A single Series object
  • Array of Series objects
  • ArrayCollection of Data Transfer Objects

Correct Answer: C

9. Recognize how to use Remote Procedure Call (RPC) services. You are accessing multiple remote methods from a WebService object. You need to defi ne different result events for each method call.Which tag nested inside the WebService tag block should you use?

  • <mx:result>
  • <mx:method>
  • <mx:operation>
  • <mx:remoteMethod>

Correct Answer: C

10. Recognize how to manage data using Flex Data Services (FDS) Your application uses the Data Management Service to manage distributed data.You have returned an instance of the AsyncToken class upon calling the DataService commit() method, using this syntax:

token = myService.commit();token.action=”saved”;

<!– You have defined a result handler method that is called upon the result event of the DataService.

The method signature is:

resultHandler(event:ResultEvent):void –>

Which expression within the handler method will return the value of the token object action property?

  • event.action
  • event.token.action
  • event.token.result.action
  • event.result.token.action

Publish your Flex application code

From Flex builder select project -> Publish application source.

Dialog box for selecting the source elements will open. By default, all project source code and assets are selected, but you can specify at your own.

If the main application is an MXML file, flex builder automatically adds the necessary code to enable the view source context menu item.

If you want to manually enable theat item, you should add the viewSourceURL attribute to the <mx:Application> tag such that it points to the index.html page in the published source code directory.

If the main application is an AS file, you'll have to enable the context menu item using AS code. this step requires the com.adobe.viewsource.ViewSource class .You should then call the static addMenuItem() method , passing it a reference to the main class instance and the URL for the source code, like so:

ViewSource.addMenuItem(this,”sourcecode/index.html”);


MXML & AS correlations





MXML is the powerful way to simplify the creation of user interfaces.


For example:


In MXML file for creating a button:


<mx:Button x=”166″ y=”56″ id=”btn” label=”Click Me”/>


In AS file for creating a button:


var btn:Button=new Button();


btn.label=”Click Me”;


“Lets see one more example:”


MXML file:


<?xml version=”1.0″ encoding=”utf-8″?>

<mx:Application xmlns:mx=”
http://www.adobe.com/2006/mxml” layout=”absolute”>

<mx:Button id=”btn”/>

</mx:Application>


AS file:


package

{

import mx.core.Application;

import mx.controls.Button;

public class example extends Application{

internal var btn:Button;

public function example(){

super();

btn=new Button();

addChild(btn);

}

}

}





Popup in Flex

CanvasPopup.mxml

<?xml version=”1.0″ encoding=”utf-8″?>
<!– We are creating a TitleWindow so that it would be draggable–>
<mx:TitleWindow xmlns:mx=”
http://www.adobe.com/2006/mxml ” width=”252″ height=”200″>
<mx:Script>
<![CDATA[
import mx.managers.PopUpManager;
public function closeThis():void
{
PopUpManager.removePopUp(this);
}
]]>
</mx:Script>
<mx:Button x=”500″ y=”150″ label=”Close” click=”closeThis()”/>
</mx:TitleWindow>

popup.mxml

<?xml version=”1.0″ encoding=”utf-8″?>
<mx:Application xmlns:mx=”
http://www.adobe.com/2006/mxml ” width=”100%” height=”100%”>
<mx:Script>
<![CDATA[
import mx.managers.PopUpManager;
public function showPopUp():void
{
var pop2:CanvasPopup = CanvasPopup(PopUpManager.createPopUp(this,CanvasPopup,true));
PopUpManager.centerPopUp(pop2);
}
]]>
</mx:Script>
<mx:Canvas>
<mx:Button x=”313″ y=”229″ label=”Show Popup” click=”showPopUp()”/>
</mx:Canvas>
</mx:Application>

Through Actionscript

CanvasPopup.mxml

<?xml version=”1.0″ encoding=”utf-8″?>
<mx:TitleWindow xmlns:mx=”
http://www.adobe.com/2006/mxml ” width=”252″ height=”200″ initialize=”init()”>
<mx:Script>
<![CDATA[
import mx.controls.Button;
import mx.controls.Alert;
import mx.managers.PopUpManager;
import flash.events.MouseEvent;
private function closeThis(e:MouseEvent):void
{
PopUpManager.removePopUp(this);
}
private function init():void{
var btn:Button = new Button()
btn.move(500,150);
btn.label=”Close”;
btn.addEventListener(MouseEvent.CLICK,closeThis);
addChild(btn);
}
]]>
</mx:Script>
</mx:TitleWindow>

popup.mxml

<?xml version=”1.0″ encoding=”utf-8″?>
<mx:Application xmlns:mx=”
http://www.adobe.com/2006/mxml ” width=”100%” height=”100%” initialize=”init()”>
<mx:Script>
<![CDATA[
import mx.controls.Button;
import mx.managers.PopUpManager;
import flash.events.MouseEvent;
private function showPopUp(e:MouseEvent):void
{
var pop2:CanvasPopup = CanvasPopup(PopUpManager.createPopUp(this,CanvasPopup,true));
PopUpManager.centerPopUp(pop2);
}
private function init():void{
var btn:Button=new Button()
btn.move(313,229);
btn.label=”Show Popup”;
btn.addEventListener(MouseEvent.CLICK, showPopUp);
addChild(btn);
}
]]>
</mx:Script>
</mx:Application>


seperate the code and UI view





How to create AS files for a tab navigator.


// main.mxml


<?xml version=”1.0″ encoding=”utf-8″?>

<mx:Application xmlns:mx=”
http://www.adobe.com/2006/mxml” layout=”absolute”

backgroundGradientColors=”[#ffffff, #c0c0c0]” xmlns:local=”*”>

<mx:TabNavigator x=”10″ y=”10″ width=”200″ height=”200″>

<local:FirstTab label=”Tab 1″ width=”100%” height=”100%”/>

<mx:Canvas label=”Tab 2″ width=”100%” height=”100%”/>

</mx:TabNavigator>

</mx:Application>


// firstTab.mxml


<?xml version=”1.0″ encoding=”utf-8″?>

<FirstTabClass xmlns=”tab.*” xmlns:mx=”
http://www.adobe.com/2006/mxml” width=”250″ height=”150″>

<mx:Button label=”Button” horizontalCenter=”0″ verticalCenter=”0″ id=”button”/>

</FirstTabClass>


// FirstTabClass.as


package tab

{

import mx.containers.Canvas;

import mx.controls.Button;

import mx.events.FlexEvent;

import flash.events.MouseEvent;



public class FirstTabClass extends Canvas

{

// the variable name should correspond to the id of the button object in the component

public var button:Button;



public function FirstTabClass() {

addEventListener(FlexEvent.CREATION_COMPLETE, creationCompleteHandler);

}



private function creationCompleteHandler(event:FlexEvent):void {

button.addEventListener(MouseEvent.CLICK, buttonClickHandler);

}



private function buttonClickHandler(event:MouseEvent):void {

trace(”FirstTabClass”);

}

}

}




Hide/show effect in Flex

<?xml version=”1.0″ encoding=”utf-8″?>
<mx:Application xmlns:mx=”
http://www.adobe.com/2006/mxml ” layout=”vertical” creationComplete=”creationCompleteHandler()”>
<mx:Script>
<![CDATA[
// we need to import these modules to be able to create our own effects
import mx.effects.Glow;
import mx.effects.Fade;
import mx.effects.Parallel;

import mx.controls.Button;
import mx.containers.Canvas;

private var myCanvas:Canvas = new Canvas();
private var myButton:Button = new Button();
private var myParallel:Parallel = new Parallel(myCanvas);
private var myVisible:Boolean = true;

// we play the parallel effect when the user clicks the button
private function buttonHandler(event:MouseEvent):void {
if (myVisible) {
// play the effect in reverse, hiding the canvas in the process
myParallel.play(null, true);
myVisible = false;
} else {
// play the effect normaly, making the canvas appear with our Fade and Glow effects applied
myParallel.play();
myVisible = true;
}
}

private function creationCompleteHandler():void {
// define properties for our Canvas
myCanvas.setStyle(”backgroundColor”, 0×000000);
myCanvas.width = 250;
myCanvas.height = 250;

// define properties for our Button and its click event handler
myButton.label = “Hide/Show”;
myButton.addEventListener(MouseEvent.CLICK, buttonHandler);

// define our Fade effect
var myFade:Fade = new Fade();
myFade.alphaFrom = 0;
myFade.alphaTo = 1;
myFade.duration = 1000;

// define our Glow effect
var myGlow:Glow = new Glow();
myGlow.alphaFrom = 1;
myGlow.alphaTo = 0;
myGlow.blurXFrom = 0;
myGlow.blurXTo = 150;
myGlow.blurYFrom = 0;
myGlow.blurYTo = 150;
myGlow.color = 0×000000;

// add our Fade and Glow effects to our Parallel object
myParallel.addChild(myFade);
myParallel.addChild(myGlow);

// add our Canvas and Button objects to the main application
this.addChild(myCanvas);
this.addChild(myButton);
}
]]>
</mx:Script>
</mx:Application>


XML parsing in Flex





////// img.xml /////////


<images>

<image>

<id>1</id>

<filename>image1.jpg</filename>

</image>

<image>

<id>2</id>

<filename>image2.jpg</filename>

</image>

<image>

<id>3</id>

<filename>image3.jpg</filename>

</image>

<image>

<id>4</id>

<filename>image4.jpg</filename>

</image>

<image>

<id>5</id>

<filename>image5.jpg</filename>

</image>

</images>


////// main.mxml ////////


import mx.collections.ArrayCollection;

import mx.rpc.events.ResultEvent;

import mx.rpc.http.HTTPService;

private var images:ArrayCollection = new ArrayCollection();

private function loadData():void {

var data:HTTPService = new HTTPService();

data.addEventListener(ResultEvent.RESULT,

function(event:ResultEvent):void {

images = event.result.images.image;

var a:Array = new Array();

// here's the important part, using the for each loop to access the loaded data

for each (var item:Object in images) {

item['filename'] = item['filename'];

a.push(item['filename']);

}

trace(a);

}

);

data.url = “img.xml”;

data.send();


}


Output would be:


image1.jpg, image2.jpg, image3.jpg, image4.jpg, image5.jpg



send Params from Flex-to-Flex

/// Main.mxml //////////
<?xml version=”1.0″ encoding=”utf-8″?>
<mx:Application xmlns:mx=”
http://www.adobe.com/2006/mxml “>
<mx:Script>
<![CDATA[
[Bindable]
public var param:Number= 72;
]]>
</mx:Script>
<mx:SWFLoader source=”Sample.swf”/>
</mx:Application>

/// Sample.mxml //////////
<?xml version=”1.0″ encoding=”utf-8″?>
<mx:Application xmlns:mx=”
http://www.adobe.com/2006/mxml ” layout=”absolute”>
<mx:Script>
<![CDATA[
import mx.core.Application;
]]>
</mx:Script>
<mx:TextInput text=”{Application.application.param}”/>
</mx:Application>


Manually handle component events





Its not necessary to handle the events inside the tags only, you can even handle them manually as well as follows:

<?xml version=”1.0″?>

<!– events/DispatchEventExample.mxml –>

<mx:Application xmlns:mx=”
http://www.adobe.com/2006/mxml” initialize=”createListener(event)”>

<mx:Script>

<![CDATA[

import mx.controls.Alert;

private function createListener(e:Event):void {

// b1.addEventListener(MouseEvent.MOUSE_OVER, myEventHandler);

b1.addEventListener(MouseEvent.CLICK, myClickHandler);

}

private function myEventHandler(e:Event):void {

var result:Boolean = b1.dispatchEvent(new MouseEvent(MouseEvent.CLICK, true, false));

}

private function myClickHandler(e:Event):void {

Alert.show(”Triggered by the ” + e.type + ” event”);

}

]]>

</mx:Script>

<mx:Button id=”b1″ label=”Click Me”/>

</mx:Application>



check out one more example:



<?xml version=”1.0″?>

<!– events/DispatchCustomizedEvent.mxml –>

<mx:Application xmlns:mx=”
http://www.adobe.com/2006/mxml” creationComplete=”addListeners()”>

<mx:Script>

<![CDATA[

private function customLogEvent(e:MouseEvent):void {

ta1.text = e.currentTarget.id + “:” + e.type + “:” + e.shiftKey;

// Remove current listener to avoid recursion.

e.currentTarget.removeEventListener(”doubleClick”,customLogEvent);

}

private function handleEvent(e:MouseEvent):void {

// Add new handler for custom event about to be dispatched.

e.currentTarget.addEventListener(”doubleClick”,customLogEvent);

// Create new event object.

var mev:MouseEvent = new MouseEvent(”doubleClick”);

// Customize event object.

mev.shiftKey = true;

// Dispatch custom event.

e.currentTarget.dispatchEvent(mev);

}

private function addListeners():void {

b1.addEventListener(”click”,handleEvent);

b2.addEventListener(”click”,handleEvent);

}

]]>

</mx:Script>

<mx:VBox id=”vb1″>

<mx:Button id=”b1″ label=”B1″/>

<mx:Button id=”b2″ label=”B2″/>

<mx:TextArea id=”ta1″/>

</mx:VBox>

</mx:Application>




How to remove toolbar and restrict the size of browser window in Flex :

There are so many methods of doing this :

<?xml version=”1.0″ encoding=”utf-8″?>
<mx:Application xmlns:mx=”
http://www.adobe.com/2006/mxml ” layout=”absolute”>

Normal Way:
<mx:Button click=”open()” label=”open”/>

Through Javascript:
<mx:Button click=”openJS()” label=”openJS” x=”59″/>

Through External Interface:
<mx:Button click=”openEI()” label=”openEI” x=”134″/>

Through FSCommand:
<mx:Button click=”openFS()” label=”openFS” x=”218″/>
<mx:Script>
<![CDATA[
private var str:String=”
http://www.google.com “
private function openJS():void{
var jscommand:String = “window.open('”+str+”‘,'win','height=200,width=300,toolbar=no,scrollbars=no');”;
var
url:URLRequest = new URLRequest(”javascript:” + jscommand + ” void(0);”); navigateToURL(url, “_self”);
}
private function open():void{
var
url:URLRequest = new URLRequest(str);
navigateToURL(url, “_blank”);
}
private function openEI():void{
if (ExternalInterface.available) {
ExternalInterface.call(”window.open”, str, “win”, “height=200,width=300,toolbar=no,scrollbars=no”);
}
}
private function openFS():void{
fscommand(”openWindow”, str+”winheight=200,width=300,toolbar=no,scrollbars=yes”);
}
]]>
</mx:Script>
</mx:Application>

Since External Interface is not supported for all browsers, its recommended that you first check to see if it is supported. If not, you might want to consider an alternate approach.


How to work with Repeaters in Flex






<?xml version=”1.0″?>

<mx:Application xmlns:mx=”
http://www.adobe.com/2006/mxml“>

<mx:Script>

<![CDATA[

import mx.controls.Alert;

[Bindable]

private var dp:Array = [1, 2, 3, 4, 5, 6, 7, 8]; // you can add number of elements you want

]]>

</mx:Script>

<mx:Panel title=”Repeater Example” width=”75%” height=”75%” paddingTop=”10″ paddingLeft=”10″ paddingRight=”10″ paddingBottom=”10″>

<mx:Tile direction=”horizontal” borderStyle=”inset” horizontalGap=”10″ verticalGap=”15″ paddingLeft=”10″ paddingTop=”10″ paddingBottom=”10″ paddingRight=”10″>

<mx:Repeater id=”rp” dataProvider=”{dp}”>

<mx:Button height=”49″ width=”50″ label=”{String(rp.currentItem)}” click=”Alert.show(String(event.currentTarget.getRepeaterItem()) + ‘ pressed')”/>

</mx:Repeater>

</mx:Tile>

</mx:Panel>

</mx:Application>



Event Bubbling in Flex

Event bubbling:
The mechanism through which event objects are passed from the objects that generates an event up through the containership hierarchy .this architecture allows you to capture events at any level of application.Not just the object that generates an event but any of its containers.

event.target & event.currentTarget

// EventBubbling.mxml

<?xml version=”1.0″ encoding=”utf-8″?>
<mx:Application xmlns:mx=”
http://www.blogger.com/ ” layout=”vertical”>
<mx:Script>
<![CDATA[
private function btnClick(event:MouseEvent):void{
TXT.text=”Target:::”+event.target+”\n”;
}
]]>
</mx:Script>
<mx:VBox id=”VBOX” paddingBottom=”15″ paddingTop=”15″ paddingLeft=”15″ paddingRight=”15″ backgroundColor=”0xFFFFFF”>
<mx:Button id=”BTN” click=”btnClick(event)” label=”Click Me”/>
</mx:VBox>
<mx:TextArea id=”TXT” width=”300″ height=”200″/>
</mx:Application>

// Output is: whenever you clicked the button you'll get:
Target:::BTN
Target:::BTN
Target:::BTN

// EventBubbling.mxml

<?xml version=”1.0″ encoding=”utf-8″?>
<mx:Application xmlns:mx=”
http://www.blogger.com/ ” layout=”vertical” click=”btnClick(event)”>
<mx:Script>
<![CDATA[
private function btnClick(event:MouseEvent):void{
TXT.text=”Target:::”+event.target+”\n”+”Current Target:::”+event.currentTarget.id+”\n”;
}
]]>
</mx:Script>
<mx:VBox id=”VBOX” paddingBottom=”15″ paddingTop=”15″ paddingLeft=”15″ paddingRight=”15″
backgroundColor=”0xFFFFFF” click=”btnClick(event)”>
<mx:Button id=”BTN” click=”btnClick(event)” label=”Click Me”/>
</mx:VBox>
<mx:TextArea id=”TXT” width=”300″ height=”200″/>
</mx:Application>

// Output is:
Target:::BTN
Current Target:::BTN
Target:::BTN
Current Target:::VBOX
Target:::BTN
Current Target:::EventBubbling (name of the application)


Flex in FullScreen Mode

Fullscreen on clicking of a button:

<?xml version=”1.0″ encoding=”utf-8″?>
<mx:Application xmlns:mx=”
http://www.adobe.com/2006/mxml ” layout=”absolute” applicationComplete=”init()”>
<mx:Script>
<![CDATA[
import flash.display.*;
import flash.events.FullScreenEvent;
// Status FULLSCREEN:
private var FullScreenStatus:Boolean = false;
private function init():void
{
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.align = StageAlign.TOP_LEFT;
stage.addEventListener(FullScreenEvent.FULL_SCREEN, fullScreenRedraw);
}
private function fullScreenRedraw(event:FullScreenEvent):void
{
output.text = “FULLSCREEN Status: ” + String(event.fullScreen)

if (event.fullScreen == false)
disableFullScreen()
}
private function changeFullScreenStatus(e:MouseEvent):void
{
if(FullScreenStatus)
disableFullScreen()
else
enableFullScreen()
}
private function disableFullScreen():void
{
FullScreenStatus = false;
fullScreen_btn.label = “ENABLE FullScreen”;
fullScreen_btn.stage.displayState = StageDisplayState.NORMAL;
}
private function enableFullScreen():void
{
FullScreenStatus = true;
fullScreen_btn.label = “DISABLE FullScreen”;
fullScreen_btn.stage.displayState = StageDisplayState.FULL_SCREEN;
}
]]>
</mx:Script>
<mx:Button label=” FULLSCREEN” id=”fullScreen_btn” x=”46″ y=”35″ click=”changeFullScreenStatus(event)”/>
<mx:Text x=”56″ y=”65″ text=”FULLSCREEN Status” id=”output”/>
</mx:Application>

Fullscreen on Creation Complete:

<?xml version=”1.0″ encoding=”utf-8″?>
<mx:Application xmlns:mx=”
http://www.adobe.com/2006/mxml ” layout=”absolute” creationComplete=”init()”>
<mx:Script>
<![CDATA[
import flash.system.fscommand;
private function init():void{
fscommand(”fullscreen”,”true”);
}
]]>
</mx:Script>
<mx:Button x=”90″ y=”45″ label=”Hello!”/>
</mx:Application>


Cairngorm (Flex framework) in Flex





Cairngorm is one of the primary open source frameworks for application architecture in Flex. Cairngorm is based on the MVC Model . In complex computer applications that present a large amount of data to the user, a developer often wishes to separate data (model) and user interface(UI-view) concerns, so that changes to the user interface will not affect data handling, and that the data can be reorganized without changing the user interface. The model-view-controller solves this problem by decoupling data access and business logic from data presentation and user interaction , by introducing an intermediate component: the controller .



  • Model : The domain-specific representation of the information on which the application operates. Domain logic adds meaning to raw data (e.g., calculating if today is the user's birthday, or the totals, taxes and shipping charges for shopping cart items). Many applications use a persistent storage mechanism (such as a database) to store data. MVC does not specifically mention the data access layer because it is understood to be underneath or encapsulated by the Model.
  • View : Renders the model into a form suitable for interaction, typically a UI element. Multiple views can exist for a single model for different purposes.
  • Controller : Processes and responds to events, typically user actions, and may invoke changes on the model.


How Flex fits the MVC models??

The goal of the Model-View-Controller (MVC) architecture is that by creating components with a well-defined and limited scope in your application, you increase the reusability of the components and improve the maintainability of the overall system .Using the MVC architecture, you can partition your system into three categories of components:



  • Model components : Encapsulates data and behaviors related to the data.
  • View components : Defines your application's user interface.
  • Controller components : Handles the data interconnectivity in your application.


For example , with the MVC design, you could implement a data-entry form that has three distinct pieces:



  • The model consists of XML data files or the remote data service calls to hold the form data.
  • The view is the presentation of any data and display of all user interface elements.
  • The controller holds the user interface logic.


Although you can consider a Flex application as part of the View in a distributed MVC architecture, you can use Flex to implement the entire MVC architecture on the client. A Flex application has its own view components that define the user interface, model components to represent data, and controller components responsible for the communication with back-end systems. This client-side separation of task is not available in HTML.



MovieClip vs Sprite

Display Objects
One of the changes in ActionScript 3 is to be working with display objects.

MovieClip (flash.display.MovieClip)
Sprite (flash.display.Sprite) – like a MovieClip but with no frames. They are a new kind of light-weight MovieClip that doesn’t technically have any frames. Since MovieClip instances you create dynamically through ActionScript cannot have frames anyway, chances are you’d want to use a Sprite in place of a MovieClip for all dynamically created MovieClip instances.
Shape (flash.display.Shape) – like a Sprite but with no mouse or keyboard interactivity. They are like Sprites but they offer mouse or keyboard interactivity. In other words, these display objects cannot receive events like mouseDown or keyUp. Shape instances cannot contain any other kind of display objects nor have children of their own. You can only draw vector shapes within them using the vector drawing API‘s (beginFill, lineTo, endFill, etc). This comes as an advantage to Shapes since they use less memory and are more efficient than MovieClips and Sprites.
Bitmap (flash.display.Bitmap) – like a Sprite but used only for displaying bitmap images. They are much like Shapes except instead of being able to contain vector drawings; they contain bitmap images defined by a BitmapData instance. They, too, cannot contain any other display objects or children. They can interact with the mouse and keyboard.
Loader (flash.display.Loader) – like a Sprite but used specifically to display and contain loaded content (SWFs and images).Like Sprite, has no timeline, but is designed specifically to facilitate the loading of external display content such as external SWFs and bitmap images. When loaded, those assets displayed in the Loader instance and are accessible through the Loader’s content property.
Why, when and how should people extend the Sprite in a class vs. the MovieClip class?
It seems like they’re the same thing… but I know that a sprite is at a lower level… what benefits do you get from using sprites instead of movieclips? Or movieclips instead of sprites?

Movie clips are sprites with a timeline and methods/properties to manipulate it. Use Sprite unless you require a timeline. And if you don’t require the functionality of DisplayObjectContainer (child movie clips) and InteractiveObject (mouse events, enterFrame, etc) then you should use Shape, which is light weight and simple but Shapes do have enterFrame events ;) just not the interactive stuff - mouse or keyboard interaction :) The MovieClip class is dynamic, to make the transition to AS3 easier, whereas the Sprite class are static. You can use Sprite as a class for movieclip symbols in your timeline but you cannot navigate to any frame beyond frame 1 and you cannot have ActionScript placed on that timeline. For any of that, you would want to stick to MovieClip. And if not using any timeline features there’s no point in using MovieClip… unless you want an automatically dynamic sprite without making your own subclass
Sprite is a little less memory because they don’t have to worry about frames. If u want to draw stuffs and don’t need mouse or keyboard events then its wise use shape…

e4x (ECMAScript for XML )





e4x is a programming language extension that adds native XML support to ECMAscript. It does this by providing access to the XML document in a form that feels natural for ECMAscript programmers. The goal is to provide a simpler API for accessing XML documents, than other common APIs, such as DOM or XSLT.


Lets take a look at a few examples of how you can read XML data using E4X.

As in the current player, you'll be able to create variables of type XML by parsing a String. But XML literals will now be supported as well:



    var employees:XML =

        <employees>

            <employee ssn=”123-123-1234″>

                <name first=”John” last=”Doe”/>

                <address>

                    <street>11 Main St.</street>

                    <city>San Francisco</city>

                    <state>CA</state>

                    <zip>98765</zip>

                </address>

            </employee>

            <employee ssn=”789-789-7890″>

                <name first=”Mary” last=”Roe”/>

                <address>

                    <street>99 Broad St.</street>

                    <city>Newton</city>

                    <state>MA</state>

                    <zip>01234</zip>

                </address>

            </employee>

        </employees>;



Instead of using DOM-style APIs like firstChild, nextSibling, etc., with E4X you just “dot down” to grab the node you want. Multiple nodes are indexable with [n], similar to the elements of an Array:



    trace(employees.employee[0].address.zip);

    —

    98765



To grab an attribute, you just use the .@ operator:



    trace([EMAIL PROTECTED]);

    —

    789-789-7890



If you don't pick out a particular node, you get all of them, as an indexable list:



    trace(employees.employee.name);

    —

    <name first=”John” last=”Doe”/>

    <name first=”Mary” last=”Roe”/>



(And note that nodes even toString() themselves into formatted XML!)



A handy double-dot operator lets you omit the “path” down into the XML _expression_, so you could shorten the previous three examples to



    trace(employees..zip[0]);

    trace([EMAIL PROTECTED]]);

    trace(employees..name);



You can use a * wildcard to get a list of multiple nodes or attributes with various names, and the resulting list is indexable:



    trace(employees.employee[0].address.*);

    —

    <street>11 Main St.</street>

    <city>San Francisco</city>

    <state>CA</state>

    <zip>98765</zip>

    trace([EMAIL PROTECTED]);

    —

    Doe



You don't have to hard-code the identifiers for the nodes or attributes… they can themselves be variables:



    var whichNode:String = “zip”;

    trace(employees.employee[0].address[whichNode]);

    —

    98765



    var whichAttribute:String = “ssn”;

    trace([EMAIL PROTECTED]);

    —

    789-789-7890



A new for-each loop lets you loop over multiple nodes or attributes:



    for each (var ssn:XML in [EMAIL PROTECTED])

    {

        trace(ssn);

    }

    —

    123-123-1234

    789-789-7890



Most powerful of all, E4X supports “predicate filtering” using the syntax .(condition), which lets you pick out nodes or attributes that meet a condition you specify using a Boolean _expression_. For example, you can pick out the employee with a particular social security number like this, and get her state:



    var ssnToFind:String = “789-789-7890″;

    trace(employees.employee.(@ssn == ssnToFind)..state);

    —

    MA


Instead of using a simple conditional operator like ==, you can also write a complicated predicate filtering function to pick out the data you need. 

By the way, although none of my examples use XML namespaces, E4X has complete support for them. 

Compared with the current XML support in the Flash Player, E4X allows you to write less code and execute it faster because more processing can be done at the native speed of C++. 

Since E4X is so powerful, we're working to make Flex 2.0 play nicely with it. Components like List, ComboBox, and DataGrid will be able to accept E4X expressions like employees..name as a dataProvider. The <mx:XML> tag will be able to declare an E4X-style XML object in MXML. WebService and HTTPService will be able to deliver E4X-style XML objects across the wire, and they'll use the speed of E4X to do their own work (such as constructing and desconstrucing SOAP packets) faster. 

For backward compability, the new player will continue to support the old-style XML and XMLNode objects, with the one change that the old XML class will be renamed to XMLDocument. The renaming is necessary because the E4X standard specifies that the new type be called XML. So if you have XML code and you want to continue using, just use XMLDocument instead. But we'll be encouraging everyone to migrate to E4X because it is so much simpler , faster , and more expressive .




Related Flex Tutorials