Search Flex Components Free

Custom Search

December 29, 2007

Free Componet in Flex A walk through the FlexBook page flip effect

see Demo click on these links:

A walk through the FlexBook page flip effect
The code for this component is written from scratch, using AS3, flex concepts, and player 9 functionality, but it is by no means original.
The functionality is inspired by this excellent example from Macc/iparigrafika.

Free Componet in Flex FlexBook with the Landscape Zoomer

see Demo:-

Example 6: FlexBook with the Landscape Zoomer
Interested in learning how FlexBuilder works? Take a peek at this walkthrough (work in progress)

Free Componet in Flex FlexBook with the Landscape Zoomer

see Demo:

Example 6: FlexBook with the Landscape Zoomer
Interested in learning how FlexBuilder works? Take a peek at this walkthrough (work in progress)

FlexBook as an image browser

see Demo click on this link:

Example 5: FlexBook as an image browser
Here’s an example that combines the FlexBook with the Landscape Zoomer component to browse images. Turn the page until you find a picture you like, then click on the image to zoom in. Click again to zoom back out.

Free Componet in Flex FlexBook’s transparent Anatomy

Demo Click on this link:

Example 4: FlexBook’s transparent Anatomy
This example doesn’t show any new functionality, but it’s a nicely put together example of a dataDriven FlexBook, combined with a state/transition driven item renderer

Free Componet in Flex FlexBook’s styles and settings

Great Demo:

Example 3: FlexBook’s styles and settings
FlexBook supports full transparency on its pages.
This example is in honor of (and made possible by) my mom, who’s a world class medical illustrator

Free Componet in Flex FlexBook as a List

Example 2: FlexBook as a List

FlexBook Supports a wide variety of configuration options.
Play with some of them here:

Free Component FlexBook as a container

Great Demo:

FlexBook can act as a container, allowing the developer to flip through its children components:

Example 1: FlexBook as a container


FlexBook can be driven by a list of data and an itemRenderer, like a List control or DataGrid. Here’s a porfolio viewer, driven by an XML data file and an MXML component itemRenderer:

FlexBook, PageFlip Free Component

Tags: UIComponent, Pageflip, book

Website: http://quietlyscheming.com/flexbookView Sample
Turn the pageWith the FlexBook by Ely Greenfield you can do now anything what is possible with an ordinary book also in the internet... and much more.There are already a few implementations of this component in the flash world known as PageFlip. Ely Greenfield converted this useful thing into MXML. There is no wish left. You can include anything in the FlexBook not just pictures and text. A page can contain any standard Flex Component even charting components.Ely Greenfield shows a few examples for using the FlexBook at his website.

Free Flex PopUp ToolBar Component

View Samples:View Samples:<


Download PopUp ToolBar

A click in the the menu opens a new PopUp Panel. This Panel can contain your custom components. You can move, resize, minimize and close this PopUp Panel. You can choose whether your menu appears horizontal or vertical.

In depth
For each item in the menu you need to declare two components.
The first is for the icon in the toolbar, the second is for component which opens up if you click the menu item. For both Items you can use any UIComponent.
It makes sense to use for the icon the mx.controls.Button or the mx.controls.Image widget. For the second component you should use some kind of container like mx.containers.Canvas, HBox or VBox or similar. In this container you can place your own widgets or components.
The PopUp ToolBar contains two custom tags.
The first is the component itself. It has the properties:
target:UIComponent the target container where the PopUp Panel appears. If you leave this property empty, the ToolbarMenu uses its parent as default target.
dataProvider:ArrayCollection contains the ToolBarMenuItems. A ToolBarMenuItem contains a pair of two UIComponents. The first is the icon for the menu, the second is Container component for the PopUp Panel.
direction:String the two possible values are: horizontal or vertical

The second is the .
All the properties (except: event) of the ToolBarItem effect the behavior of the PopUp Panel. This component has the properties:
title:String the title of the PopUp Panel
x:Number the x position of the PopUp Panel relative to the target.
y:Number the y position of the PopUp Panel relative to the target.
width:Number the width of the PopUp Panel, the default value is 200 pixel
height:Number the height of the PopUp Panel, the default value is 200 pixel
event:String the event for the item in the menu which triggers a new PopUp Panel,
possible values are: click, doubleClick, mouseOver













Example Code:




he Popup ToolBar < ks:PopUpToolBar id="myMenu" x="135" y="10" target="{myCanvas}" paddingLeft="5" paddingTop="5" paddingBottom="5" paddingRight="5" borderStyle="solid" borderThickness="1" borderColor="#CCCCCC" dataProvider="{myDataProvider}" direction="horizontal"/>

The dataProvider for the ToolBarMenu <mx:ArrayCollection id="myDataProvider"> <ks:ToolBarItem title="Hello World" x="30" y="40" width="350" height="200" event="doubleClick"> <!-- menu icon component --> <mx:Image source="data/icons/world.gif" /> <!-- PopUp Panel component --> <mx:Label text="Hello World" /> </ks:ToolBarItem> <ks:ToolBarItem title="BackgroundColor" event="doubleClick"> <mx:Image source="data/icons/circle.gif" /> <mx:DateChooser/> </ks:ToolBarItem> </mx:ArrayCollection>

Free AutoScroll Component for Flex 2

I promised one completely free and open source Flex component each week in May, and I’m determined to deliver. So after a busy week at my .NET day job, I managed to stay up last night and make the AutoScroll component from scratch. The AutoScroll component will render a horizontal display container that scrolls according to your mouse position. You should provide it with a dataProvider and itemRenderer and it will do the rest. I wanted to extend the ListBase for this component, but I couldn’t overcome the underlying problems in time. I’ll revisit this at some point in the future, but in the mean time feel free to improve it on your own.

Image of AutoScroll Component


AutoScroll Explorer (Flash Player 9 Beta 3 Required)

View AutoScroll Explorer Source

Download AutoScroll Explorer Source

This component is licensed under a Creative Commons Attribution 2.5 License. Feel free to download and modify the code for any use as long as my name is in there somewhere. Updates and improvements to the AutoScroll component will be appended to this entry as it grows up and gets more polish.

Multiple File Upload and Download Component in Flex


Let’s say that you take a lot of pictures. You take pictures, but you don’t want to think about how to upload them. You’d really like an application to monitor a directory for new images, and then upload them to a server. That kind of rules out the browser - it’s not going to be watching a directory on your desktop for image files, and then automatically uploading them. What about Apollo though? Couldn’t an Apollo application monitor a directory for me? Sure! Let’s make it happen…To preface this little experiment, the Apollo alpha doesn’t currently support the ability to run as a background process. To that end, this application does have to be running. It can be minimized, but it does have to be running. Oh, and I should mention that this application is written entirely in HTML, CSS and JavaScript. No Flash involved here, just Apollo DHTML goodness.

The UI for this application can be pretty simple - especially since we’re talking about an application that could eventually run in the background. To that end, my HTML (view) is little more than the basic HTML page with a single DIV. We’ll eventually use that DIV to hold a list of images and render that list with nifty upload status progress bars. Wait, progress bar of an image being uploaded? I know, it’s not something you generally see in HTML because, well, because it’s not available. That type of low-level event is available to Apollo. We’ll see more about this later, but for now let’s head back to the UI.






<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Watcher</title> <script src="jquery-1.1.2.js" type="text/javascript"></script> <script src="watcher.js" type="text/javascript"></script> <link href="watcher.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="listing"></div> </body> </html>


I'm not a CSS guru. In fact, I'm rather appalled by the current state of affairs as it pertains to browser differences in CSS implementation. Since I'm building this application for Apollo however, I know that I'll be using WebKit, and that makes my job a lot easier. One single browser that runs consistently across operating systems. That I can handle. I use some absolute positioning for the list DIV and a few other items, and then I sprinkle in some relative positioning for smaller textual regions.

.bar { position: absolute; height: 6px; margin-top: 24px; border: solid 1px #446EAC; left: 28px; right: 5px; visibility: hidden; background-color: #FFFFFF; } body { background-color: #F6F5F4; font-family: Arial, Helvetica, sans-serif; font-size: 11px; color: #000000; } .icon { position: relative; margin-left: 5px; margin-top: 3px; float: left; } .item { height: 36px; border-bottom: solid; border-bottom-color: #808080; border-bottom-width: 1px; cursor: default; background-color: #FFFFFF; } #listing { border: solid; border-color: #808080; border-width: 1px; background-color: #FFFFFF; overflow: auto; position: absolute; left: 5px; bottom: 5px; right: 5px; top: 5px; } .filename { position: relative; float: left; margin-left: 4px; margin-top: 5px; clear: right; } .filename span { color: #808080; position: relative; margin-left: 5px; } .pending { position: relative; margin-left: 27px; margin-top: -1px; color: #808080; float: left; clear: left; } .progress { width: 0%; height: 100%; background-color: #AEDDF2; }

If we can think about having CSS consistency across OS thanks to the WebKit engine in Apollo, then it stands to reason that we can think about consistency with JavaScript too. While that is true, I'm not a masochist, and I have elected to use as a JavaScript library for this application. I'd be interested in your thoughts on jQuery and it's use in sample Apollo applications. Would you prefer samples be core JavaScript, or is a library acceptable? Which libraries would you prefer?


The first thing we'll do when the application starts is check for the existence of a directory on the desktop. Apollo makes this easy, without having to think about where the desktop is located and on which operating system. The File object in Apollo has a variety of static properties to common OS locations that return a File reference. In this case we can use File.desktopDirectory and file.resolve() the specific directory on the desktop that we're interested in watching.

// Watcher logic $( document ).ready( function() { // Check for directory var watching = runtime.flash.filesystem.File.desktopDirectory; watching = watching.resolve( dir ); // Create it if it doesn't exist if( !watching.exists ) { watching.createDirectory(); } // Do the initial check and updating of the UI update(); } );

Once the application is started and we've confirmed the presence of our image directory (or created it if it doesn't exist), then we move on to checking for the presence of image files. The File object has a listDirectory() method that we can use to get the contents of the directory. We don't want to upload anything other than image files however, so we'll check the file extension. This isn't particularly accurate, but it's a good start. If the item in the list of files is an image, then we can build an item to render the details and then pop it into the list. In the case that there are images, we'll start uploading the files, otherwise we'll check back every five seconds via JavaScript's setInterval() function.

// Checks the directory and updates the UI function update() { // HTML block for list item var itemo = "<div class="item">"; var icon = "<img src="image.png" width="18" height="18" class="icon" />"; var fileo = "<div class="filename">"; var sizeo = "<span>("; var sizec = " KB)</span>"; var filec = "</div>"; var pending = "<div class="pending">Upload not yet started...</div>"; var baro = "<div class="bar">"; var progress = "<div class="progress"></div>"; var barc = "</div>"; var itemc = "</div>"; var inject = null; // Get the list of image in the directory var watching = runtime.flash.filesystem.File.desktopDirectory; var list = null; // Get the directory listing watching = watching.resolve( dir ); list = watching.listDirectory(); // Remove existing item entries $( "#listing" ).empty(); // Find the actual image files for( var i = 0; i < list.length; i++ ) { if( list[i].name.toLowerCase().indexOf( ".jpg" ) >= 0 ) { // Build the item inject = itemo + icon + fileo + list[i].name + sizeo + formatSize( Math.round( list[i].size / 1000 ) ) + sizec + filec + pending + baro + progress + barc + itemc; // Inject the new item container $( "#listing" ).append( inject ); } } // Add mouse handlers to any new items $( ".item" ).mouseover( function() { $( this ).css( "backgroundColor", "#D4D5D8" ); } ); $( ".item" ).mouseout( function() { $( this ).css( "backgroundColor", "#FFFFFF" ); } ); // TODO: Show a means to remove an image when the mouse is over an item // TODO: Have image thumbnail appear when mouse is over icon // TODO: Show summary status bar with total upload progress // Determine if uploading needs to occur // Avoids refresh of list mid-upload // Can check for more later, after upload has completed if( $( ".item" ).size() > 0 ) { upload( null ); } else { // Check again at some point in the future setTimeout( "update()", interval ); } }

Rather than check the file system again before we're done uploading, I've chosen to extract the file name from the list item and then infer the path (we know where that directory on the desktop is, right?). I figure that once we're done with this batch of uploads that we'll check the file system again later for more image files. There are some shortcomings to this approach, but I'm not trying to account for every use-case with this example.


You might initially be inclined to think that we'll use an upload form in HTML to upload our files, but as mentioned previously, there's no means provided to check the progress. As it turns out the File object has an upload() method on it. The only thing the upload() method requires is a reference to a URLRequest object. This is the object that most importantly contains the URL endpoint, but it might optionally contain some additional form data. The File.upload() will actually execute a multi-part form upload to the server, and you can treat it as such once it gets there.


For this example I'm using ColdFusion on the server. This is mostly because I have it readily available, and it's only a single line of code to get the uploaded bytes and store them on disk. I like easy. You can replace this with whatever you prefer on the server.


The other important aspect to this is the additional event listeners I've put on the File object. The progress event let's me know periodically that the upload is taking place. It passes an event object that among other data, contains bytesLoaded and bytesTotal properties. I can use this information to determine a percentage of the progress and then tell the CSS on the progress bar to size itself to that percent. The complete event will fire when the upload is finished, and then we can take additional action.

// Show progress for the image being uploaded function progress( event ) { // Determine overall percentage from event properties var percent = Math.round( ( event.bytesLoaded / event.bytesTotal ) * 100 ); // Change CSS properties to show bar width based on percent $( ".progress:first" ).css( "width", percent + "%" ); }

I've chosen to call back to the upload() function when the upload operation is completed. When that event fires, it too will pass an event object along. The upload() function checks for the presence of that event object. If the event object is present, then the application knows that the upload is complete, and can clean up the file from disk. Once again the File object provides a deleteFile() method we can use for this in a simple one-liner. If the upload() method gets called an no event object is provided, then the application knows that we need to start an upload operation.

// Perform the actual upload function upload( event ) { // Variables for managing the upload // Image is a reference to a file on disk from the first item in the list var img = extractAndResolve( $( ".item:first" ).text() ); var request = null; // If there is no argument value, then upload the first item in the list if( event == null ) { // Show the upload progress bar and hide the waiting text $( ".pending:first" ).css( "visibility", "hidden" ); $( ".bar:first" ).css( "visibility", "visible" ); // Destination of uploaded file request = new runtime.flash.net.URLRequest( url ); // Attach the appropriate event listeners img.addEventListener( runtime.flash.events.ProgressEvent.PROGRESS, progress ); img.addEventListener( runtime.flash.events.Event.COMPLETE, upload ); // Upload the file img.upload( request, field, false ); } else { // Remove the first image item from the list $( ".item:first" ).remove(); // Remove the actual image from the disk img.deleteFile(); // Move onto the next image if there are any available if( $( ".item" ).size() > 0 ) { upload( null ); } else { // Keep checking for new images setTimeout( "update()", interval ); } } }

A word of caution here is that I have chosen to remove the files after they've been uploaded. If you're going to try this application out on your machine, make sure that you copy the files and not move them. This application has no mercy and will start uploading and deleting within seconds of your paste operation. User beware!


Once the upload operation is complete, and the image file has been removed from disk, the application checks for any additional items in the list. If there are none, the process of waiting five seconds and checking for more files starts all over. If there are additional items in the list (additional files), then the next item in the list will be processed (uploaded). I've chosen to always check the first item in the list, so uploading will happen from the top down.


That's all there is to it! There's a number of to-do's that I'd like to add, and I've made comments to that point, which again is all JavaScript. Since I'm using my own server for the upload, I throttle the upload image size to no more than three megabytes (3 Mb). Feel free to point the URL to your own server, or better yet Amazon S3 and not worry about it. That was beyond my scope for this little experiment. You can access the source code and application file in the archive attached to this post.


Flex 2 and FileReference API

Flash 8 introduced new FileReference and FileReferenceList classes that allow Flash applications to natively interact with remote file upload and download. As Flex 1.5 was tied to Flash Player 7, it was possible to use these features, however, it required extra code as it was necessary to tie into a native Flash 8 application. With Flex 2 and Flash Player 9, new and improved versions of FileReference and FileReferenceList classes are available allowing native and simple code from Flex to leverage these features. This TechNote explains how to use APIs in Flex 2 applications and provides a simple file uploading example.
File upload and download are popular features for inclusion in Flash/Flex applications. With Flex 1.x, these features weren't natively available. They became possible with the release of Flash Player 8, but in Flex, you have to create a wrapper object for a movie with the FileReference class, created in the Flash 8 authoring tool so that you can access the FileReference functionalities through the wrapper class. The detailed steps to use FileReferenece in Flex 1.5 are described in the following Developer Center article, Using Flash Player 8 Features in Your Flex 1.5 Application.
With Flex 2 and Flash Player 9, the newly enhanced file uploading/downloading features are natively available in Flex 2 application. There are two main classes in the flash.net package that handle file uploading and downloading in Flex 2 -- FileReference and FileReferenceList.
A FileReference object represents a physical file and you can invoke its browse method to open the file selection dialog box and to select the target file. Next, you call upload or download methods to upload or download the file. The FileReferenceList lets you select multiple files through its browse method and holds the reference in the fileList variable, which contains an array of FileReference objects. You can then loop through the list to upload or download each file. Below is a simple code snippet to upload a single file.
var req:URLRequest = new URLRequest(endpoint);
req.method = URLRequestMethod.POST;
fileRef.upload(req, param, false);
Enhancements worth mentioning include the upload method. Besides the upload target endpoint URL, it now takes two additonal input arguments -- uploadDataFieldName and testUpload. These two features were not available in the Flash 8 FileReference class.
When uploading a file, developers often request to attach additional metadata such as date/time at upload, auther name, etc. With Flash 8 FileReference, you can't attach that metadata in the POST data, other than through the URL parameter. The uploadDataFieldName parameter now allows for uploading metadata. Below is an example of the uploadDataFieldName field (name="author=John") in the network trace result.
------------Ij5GI3KM7gL6Ij5ei4Ij5ae0gL6Ef1
Content-Disposition: form-data; name="author=John"; filename="doc.pdf"
Content-Type: application/octet-stream
Notice the data field precedes the file data in the POST data instead of as the value under a standalone Part. For example, if you are using O'Reilly's file upload servlet package, the data field is available through the FilePart.getName instead of ParamPart.getStringValue.
The testUpload parameter is a Boolean argument that allows Flash Player to test the connection before actually uploading the file. If the testUpload parameter is true and the file to be uploaded is larger than 10KB, Flash Player sends a test uploadPOST operation with zero content length. If the connection is verified successfully, the player sends a secondPOST operation that contains the actual file content. This feature is only available on Windows version of the Player and for files larger than 10KB. With the Flash 8 FileReference class, a POST error message on the server side was commonly observed since the testUpload was always performed. The server script normally throws an error when getting a zero length POST operation, which is observable in log files or the standard output console. With Flash Player 9, the testUpload operation is optional, and, by default, the setting is false.
The new FileReference and FileReferenceList classes offer very powerful but extremely easy to use features for Flex 2 applications to leverage. Please refer to Flex 2 Language and ActionScript 3 API documentation for more details. A simple file uploading example is included below for demonstration purpose. It uses O'Reilly file uploading package as the server side component, which you may get from http://servlets.com/cos/.
Download the example (2K).

Multiple Flex File Upload with ColdFusion

This is another good Flex file upload example that handles both client and server ends. The server side is ColdFusion, which is very familiar to lots of Coldfusion-turned Flex developers. I think lots of people use the one as prototype and tailor it fit into their own project. If you are in a ColdFusion shop, this is an excellent start point to deal with file upload issues.

Adobe Flex 2 and ColdFusion MX 7 enable you to create applications that leverage the file I/O capabilities of Adobe Flash Player 9 to transport files from the client side to the server side with relative ease.
Through the Multi-File Upload application, you will learn how to do the following:
Use Adobe Flex Builder 2 to create a rich user interface to cue up files to upload
Perform client-side processing logic to permit only desirable file sizes and file types
Include additional variables with each file uploaded to the server
Use the ColdFusion CFFILE tag to handle files uploaded to the server
As great as this application is, be aware that it is not intended to demonstrate development best practices. Rather its purpose is to show how the technical and functional capabilities of Flex 2, Flash Player 9, and ColdFusion MX 7 file processing can improve the user experience of uploading files through a web browser.
Requirements
You may want to download and install the following software to follow along with this article:
Flex Builder 2 (SDK included)
Try
Buy
Flash Player 9
Download it now
ColdFusion MX 7.0.2
Try
Buy
Sample files:
multi_file_upload.zip (ZIP, 677K)
Prerequisite knowledge
Familiarity with general Flex concepts and ColdFusion's file management tags such as CFFILE.
Additional documentation
ColdFusion MX 7.0.2 CFFILE documentation
Flex 2 Language Reference

Flash 8 File Upload Download

As we know the Flex Upload is actually use the Flash 8 FileReference object to do the work. The guy who is writing the book ‘Flash 8 Upgrade Essentials’ provided a very detail demo showing how the upload is done within Flash 8. It gives you a good insight on what’s under the hood of Flex file handling.

Example: Uploading and downloading files
The FileIO example demonstrates techniques for perform file downloading and uploading in Flash Player. These techniques are:
Downloading files to a user's computer
Uploading files from a user's computer to a server
Cancelling a download in progress
Cancelling an upload in progress
The FileIO application files are found in the Samples/FileIO folder. The application consists of the following files:
File
Description
FileIO.mxml
The main application file consisting of the MXML user interface.
com/example/programmingas3/fileio/FileDownload.as
A class that includes methods for downloading files from a server.
com/example/programmingas3/fileio/FileUpload.as
A class that includes methods for uploading files to a server.

FileIO application overview

The File IO application contains the user interface that allows a user to upload or download files using Flash Player. The application first defines a couple of custom components, FileUpload and FileDownload, which can be found in the com.example.programmingas3.fileio package. Once each custom component dispatches its contentComplete event, the component's init() method is called and passes references to a ProgressBar and Button component instance, which allow users to see the file's upload or download progress or cancel the file transfer in progress.

The relevant code from the FileIO.mxml file is as follows:

<example:FileUpload id="fileUpload" creationComplete="fileUpload.init(uploadProgress, cancelUpload);" /> <example:FileDownload id="fileDownload" creationComplete="fileDownload.init(downloadProgress, cancelDownload);" />

The following code shows the Upload File panel, which contains a progress bar, and two buttons. The first button, startUpload , calls the FileUpload.startUpload() method, which calls the FileReference.browse() method. The following excerpt shows the code for the Upload File panel:

<mx:Panel title="Upload File" paddingTop="10" paddingBottom="10" paddingLeft="10" paddingRight="10"> <mx:ProgressBar id="uploadProgress" label="" mode="manual" /> <mx:ControlBar horizontalAlign="right"> <mx:Button id="startUpload" label="Upload..." click="fileUpload.startUpload();" /> <mx:Button id="cancelUpload" label="Cancel" click="fileUpload.cancelUpload();" enabled="false" /> </mx:ControlBar> </mx:Panel>

This code places a ProgressBar component instance and two Button component button instances on the Stage. When the user clicks the Upload button ( startUpload) , an operating system dialog box is launched that allows the user to select a file to upload to a remote server. The other button, cancelUpload , is disabled by default, although when a user begins a file upload, the button becomes enabled and allows the user to abort the file transfer at any time.

The code for the Download File panel is as follows:

<mx:Panel title="Download File" paddingTop="10" paddingBottom="10" paddingLeft="10" paddingRight="10"> <mx:ProgressBar id="downloadProgress" label="" mode="manual" /> <mx:ControlBar horizontalAlign="right"> <mx:Button id="startDownload" label="Download..." click="fileDownload.startDownload();" /> <mx:Button id="cancelDownload" label="Cancel" click="fileDownload.cancelDownload();" enabled="false" /> </mx:ControlBar> </mx:Panel>

This code is very similar to the file upload code. When the user clicks the Download button, ( startDownload ), the FileDownload.startDownload() method is called, which begins downloading the file specified in the FileDownload.DOWNLOAD_URL variable. As the file downloads, the progress bar updates, showing what percentage of the file has downloaded. The user can cancel the download at any point by clicking the cancelDownload button, which immediately stops the file download in progress.

Downloading files from a remote server

Downloading of files from a remote server is handled by the flash.net.FileReference class and the custom com.example.programmingas3.fileio.FileDownload class. When the user clicks the Download button, Flash Player begins to download the file specified in the FileDownload class's DOWNLOAD_URL variable.

The FileDownload class begins by defining four variables within the com.example.programmingas3.fileio package, the following code shows:

/** * Hard-code the URL of file to download to user's computer. */ private const DOWNLOAD_URL:String = "http://www.yourdomain.com/file_to_download.zip"; /** * Create a FileReference instance to handle the file download. */ private var fr:FileReference; /** * Define reference to the download ProgressBar component. */ private var pb:ProgressBar; /** * Define reference to the "Cancel" button which will immediately stop * the current download in progress. */ private var btn:Button;

The first variable, DOWNLOAD_URL , contains the path to the file, which gets downloaded onto the user's computer when the user clicks the Download button in the main application file.

The second variable, fr , is a FileReference object that gets initialized within the FileDownload.init() method and will handle the downloading of the remote file to the user's computer.

The last two variables, pb and btn , contain references to ProgressBar and Button component instances on the Stage, which get initialized by the FileDownload.init() method.

Initializing the FileDownload component

The FileDownload component is initialized by calling the init() method in the FileDownload class. This method takes two parameters, pb and btn , which are ProgressBar and Button component instances, respectively.

The code for the init() method is as follows:

/** * Set references to the components, and add listeners for the OPEN, * PROGRESS, and COMPLETE events. */ public function init(pb:ProgressBar, btn:Button):void { /* Set up the references to the progress bar and cancel button, which are passed from the calling script. */ this.pb = pb; this.btn = btn; fr = new FileReference(); fr.addEventListener(Event.OPEN, openHandler); fr.addEventListener(ProgressEvent.PROGRESS, progressHandler); fr.addEventListener(Event.COMPLETE, completeHandler); }

Beginning the file download

When the user clicks the Download Button component instance on the Stage, the startDownload() method is to initiate the file download process. The following excerpt shows the startDownload() method:

/** * Begin downloading the file specified in the DOWNLOAD_URL constant. */ public function startDownload():void { var request:URLRequest = new URLRequest(); request.url = DOWNLOAD_URL; fr.download(request); }

First, the startDownload() method creates a new URLRequest object, and sets the target URL to the value specified by the DOWNLOAD_URL variable. Next, the FileReference.download() method is called, and the newly created URLRequest object is passed as a parameter. This causes the operating system to display a dialog box on the user's computer prompting them to select a location to save the requested document. Once the user selects a location, the open event ( Event.OPEN ) is dispatched and the openHandler() method is invoked.

The openHandler() method sets the text format for the ProgressBar component's label property, and enables the Cancel button, which allows the user to immediately stop the download in progress. The openHandler() method is as follows:

/** * When the OPEN event has dispatched, change the progress bar's label * and enable the "Cancel" button, which allows the user to abort the * download operation. */ private function openHandler(event:Event):void { pb.label = "DOWNLOADING %3%%"; btn.enabled = true; }

Monitoring a file's download progress

As a file downloads from a remote server to the user's computer, the progress event ( ProgressEvent.PROGRESS ) is dispatched at regular intervals. Whenever the progress event is dispatched, the progressHandler() method is invoked and the ProgressBar component instance on the Stage is updated. The code for the progressHandler() method is as follows:

/** * While the file is downloading, update the progress bar's status. */ private function progressHandler(event:ProgressEvent):void { pb.setProgress(event.bytesLoaded, event.bytesTotal); }

The progress event contains two properties, bytesLoaded and bytesTotal , which are used to update the ProgressBar component on the Stage. This gives the user a sense of how much of the file has already finished downloading and how much remains. The user can abort the file transfer at any time by clicking the Cancel button below the progress bar.

If the file is downloaded successfully, the complete event ( Event.COMPLETE ) invokes the completeHandler() method, which notifies the user that the file has completed downloading and disables the Cancel button. The code for the completeHandler() method is as follows:

/** * Once the download has completed, change the progress bar's label one * last time and disable the "Cancel" button since the download is * already completed. */ private function completeHandler(event:Event):void { pb.label = "DOWNLOAD COMPLETE"; btn.enabled = false; }

Cancelling a file download

A user can abort a file transfer and stop any further bytes from being downloaded at any time by clicking the Cancel button on the Stage. The following excerpt shows the code for cancelling a download:

/** * Cancel the current file download. */ public function cancelDownload():void { fr.cancel(); pb.label = "DOWNLOAD CANCELLED"; btn.enabled = false; }

First, the code stops the file transfer immediately, preventing any further data from downloading. Next, the progress bar's label property is updated to notify the user that the download has been successfully cancelled. Finally, the Cancel button is disabled, which prevents the user from clicking the button again until they attempt to download the file again.

Uploading files to a remote server

The file upload process is very similar to the file download process. The FileUpload class declares the same four variables, as shown in the following code:

private const UPLOAD_URL:String = "http://www.yourdomain.com/your_upload_script.cfm"; private var fr:FileReference; private var pb:ProgressBar; private var btn:Button;

Unlike the FileDownload.DOWNLOAD_URL variable, the UPLOAD_URL variable contains the URL to the server-side script that will upload the file from the user's computer. The remaining three variables behave the same as their counterparts in the FileDownload class.

Initializing the FileUpload component

The FileUpload component contains an init() method, which gets called from the main application. This method takes two parameters, pb and btn , which are references to a ProgressBar and Button component instance on the Stage. Next, the init() method initializes the FileReference object defined earlier in the FileUpload class. Finally, the method assigns four event listeners to the FileReference object. The code for the init() method is as follows:

public function init(pb:ProgressBar, btn:Button):void { this.pb = pb; this.btn = btn; fr = new FileReference(); fr.addEventListener(Event.SELECT, selectHandler); fr.addEventListener(Event.OPEN, openHandler); fr.addEventListener(ProgressEvent.PROGRESS, progressHandler); fr.addEventListener(Event.COMPLETE, completeHandler); }

Beginning a file upload

The file upload is initiated when the user clicks on the Upload button on the Stage, which invokes the FileUpload.startUpload() method. This method calls the browse() method of the FileReference class which causes the operating system to display a system dialog box prompting the user to select a file to upload to the remote server. The following excerpt shows the code for the startUpload() method:

public function startUpload():void { fr.browse(); }

Once the user selects a file to upload, the select event ( Event.SELECT ) is dispatched, causing the selectHandler() method to be invoked. The selectHandler() method creates a new URLRequest object and sets the URLRequest.url property to the value of the UPLOAD_URL constant defined earlier in the code. Finally, the FileReference object uploads the selected file to the specified server-side script. The code for the selectHandler() method is as follows:

private function selectHandler(event:Event):void { var request:URLRequest = new URLRequest(); request.url = UPLOAD_URL; fr.upload(request); }

The remaining code in the FileUpload class is the same as the code defined in the FileDownload class. If a user wishes to terminate the upload at any point, they can click the Cancel button, which sets the label on the progress bar and stops the file transfer immediately. The progress bar gets updated whenever the progress event ( ProgressEvent.PROGRESS ) is dispatched. Similarly, once the upload has completed, the progress bar is updated to notify the user that the file has uploaded successfully. The Cancel button is then disabled until the user begins a new file transfer.

File Uploads with PHP and Flex

Structure
The PHP scripts used in our Flex applications for file uploads are semi-modular. They are based on switch statements which evaluate the variable "request." We found this to be a simple and effective way to manage communication between the Flex application and the server. For example, if we had a "user.php" page, and wanted to add a new user to our database, we would make a "case 'add'" in our switch statement, and inserted the code for processing a database request.
Feedback
We also soon found that it was important to have good communication between Flex and the server so we could prevent and debug errors efficiently. We did this by creating a function that ran at the end of every page to construct an XML that contained the feedback for Flex. The XML structure was very generic, including a tag which containted a boolean value, followed by data or, in the case of false in the success tag, nodes with specific errors to report.
Example
Here's an example PHP that could be used in the Flex application to upload a file:

<?php

$errors = array();
$data = "";
$success = "false";

function return_result($success,$errors,$data) {
echo("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
?>
<results>
<success><?=$success;?></success>
<?=$data;?>
<?=echo_errors($errors);?>
</results>
<?
}

function echo_errors($errors) {

for($i=0;$i<count($errors);$i++) {
?>
<error><?=$errors[$i];?></error>
<?
}

}

switch($_REQUEST['action']) {

case "upload":

$file_temp = $_FILES['file']['tmp_name'];
$file_name = $_FILES['file']['name'];

$file_path = $_SERVER['DOCUMENT_ROOT']."/myFileDir";

//checks for duplicate files
if(!file_exists($file_path."/".$file_name)) {

//complete upload
$filestatus = move_uploaded_file($file_temp,$file_path."/".$file_name);

if(!$filestatus) {
$success = "false";
array_push($errors,"Upload failed. Please try again.");
}

}
else {
$success = "false";
array_push($errors,"File already exists on server.");
}

break;

default:
$success = "false";
array_push($errors,"No action was requested.");

}

return_result($success,$errors,$data);

?>

Flex upload component



File Uploaded Component Demo:



One of the things that we needed to accomplish in both our Flex applications was the ability for the user to upload files to the server. Of course, Flex by itself can't upload and post files to a server without the help of a server-side script. We used PHP.Check out a quickly-developed Flex application that manages multiple file uploads and processes them through a PHP file (right-click in the application to view the source). Or, you can check out an explanation and strategy we used for the PHP.

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…

Related Flex Tutorials