Tuesday, April 28, 2009

Loading a web page from Flex

ActionScript 3.0. Developers now have to use the new navigateToURL method to load a web page from a Flex application.The navigateToURL method loads a document from a specified URL. You can use it to load the document in the same or a new browser window, and you can optionally pass variables with the URL.you can also use the method to call a JavaScript function on the web page hosting the SWF file. You can use the navigateToURL method in the following way:

navigateToURL(request, window);

The first argument, request, is a URLRequest object that specifies which web page to load. The
window argument determines how the page loads, and it can be one of the following string values:
_self, _blank, _parent, or _top.

To open the google web site in a new web browser window from a Flex application, you could
use the following lines of ActionScript:

var site:URLRequest = new URLRequest("http://www.google.com");
navigateToURL(site, "_blank");

Sending variables when calling a web page

Some Flex applications need to send variables to the web page that hosts the SWF file.
Whatever your need, one approach is to use the navigateToURL method to pass the values. There are two ways to do this:
1. Append variables to the URL, as in a GET operation.
2. Use a URLVariables object with POST.

You can add querystring variables from Flex by referring to the variable name at the end of the URL, as shown here:

var isbn:String = "1590597338";
var request:URLRequest =
new URLRequest("http://www.friendsofed.com/book.html?isbn=" + isbn);

This has the same effect as using HTTP GET to send form variables.

You can also create a new URLVariables object and pass the variables from Flex that way. The following example shows how to POST username and password variables with a URLRequest:

var site:URLRequest = new URLRequest("http://www.friendsofed.com");
var urlVars:URLVariables = new URLVariables();
site.method = "POST";
urlVars.username = "sas";
urlVars.password= "1234";
site.data = urlVars;
navigateToURL(site);

you’ll need to import the relevant classes, including the following:

import flash.net.navigateToURL;
import flash.net.URLRequest;
import flash.net.URLVariables;

You can also use the URLVariables class to send values to a server-side script.

Calling JavaScript with navigateToURL

Instead of loading a web page, you can call a JavaScript function with the navigateToURL method. To do this, don’t specify a URL. Use navigateToURL to reference a javascript command or function on the page containing the SWF file:

var jsRequest:URLRequest = new URLRequest("javascript: doWork();");

The preceding line calls the doWork JavaScript function in the web page that hosts the SWF file. Be aware that this approach might not work in all browsers, and security settings might prevent the JavaScript code from executing. A more robust approach is to use the External API.

Sending variables into a SWF file

In some cases, the hosting web page needs to send values into a Flex application. You might do this if you used server-side code to log in and you want to indicate to the Flex application that the user has logged in privileges. You could also use values from the web page to load a specific Flex application state.

there are two main approaches to sending variables into a SWF file so they can be used in your application:

Using querystring parameters when loading the SWF file
Using flashVars

Using querystring parameters
Querystring parameters are name-value variable pairs that are added at the end of a URL or file name;
for example:

mySWF.swf?userID=1234&admin=true

Once you add these parameters to the end of the SWF file name, they are accessible as variables in your Flex application.

Manually adding drag-and-drop support

To support drag-and-drop operations with non-list-based components, or to explicitly control drag and drop with list-based controls, you must handle the drag and drop events.

Classes used in drag-and-drop operations

You use the following classes to implement the drag-and-drop operation:

Class

Function

DragManager

Manages the drag-and-drop operations; for example, its doDrag() method starts the drag operation.

DragSource

Contains the data being dragged. It also provides additional drag management features, such as the ability to add a handler that is called when data is requested.

DragEvent

Represents the event object for all drag-and-drop events.



A component that acts as a drag initiator handles the following events to manage the drag-and-drop operation:

mouseDown and mouseMove,

dragStart

dragComplete.

The mouseDown event is dispatched when the user selects a control with the mouse and holds down the mouse button. The mouseMove event is dispatched when the mouse moves.

dragStart event is Dispatched by a list-based component when a drag operation starts. This event is used internally by the list-based controls; you do not handle it when implementing drag and drop.

dragComplete event is dispatched when a drag operation completes, either when the drag data drops onto a drop target, or when the drag-and-drop operation ends without performing a drop operation.

You can use this event to perform any final cleanup of the drag-and-drop operation.

When adding drag-and-drop support to a component, you must implement an event handler for either the mouseDown or mouseMove event, and optionally for the dragComplete event. When you set the dragEnabled property to true for a list-based control, Flex automatically adds event handlers for the dragStart and dragComplete events.

Drag-and-drop events for a drop target

To use a component as a drop target, you handle the following events:

dragEnter event :

Dispatched when a drag proxy moves over the drop target from outside the drop target.

A component must define an event handler for this event to be a drop target. The event handler determines whether the data being dragged is in an accepted format. To accept the drop, the event handler calls the DragManager.acceptDragDrop() method. You must call the DragManager.acceptDragDrop() method for the drop target to receive the dragOver, dragExit, and dragDrop events.

In the handler, you can change the appearance of the drop target to provide visual feedback to the user that the component can accept the drag operation. For example, you can draw a border around the drop target, or give focus to the drop target.

dragOver event is :

Dispatched while the user moves the mouse over the target, after the dragEnter event.

You can handle this event to perform additional logic before allowing the drop operation, such as dropping data to various locations within the drop target, reading keyboard input to determine if the drag-and-drop operation is a move or copy of the drag data, or providing different types of visual feedback based on the type of drag-and-drop operation.

dragDrop event is dispatched when the user releases the mouse over the drop target.

dragExit event is dispatched

when the user moves the drag proxy off of the drop target, but does not drop the data onto the target.

You can use this event to restore the drop target to its normal appearance if you modified its appearance in response to a dragEnter event or other event.

When adding drag-and-drop support to a nonlist-based component, you must implement an event handler for the dragEnter and dragDrop events, and optionally for the other events.

drag and drop

The drag-and-drop operation lets you move data from one place in an Adobe® Flex™ application to another. It is especially useful in a visual application where you can drag data between two lists, drag controls in a container to reposition them, or drag Flex components between containers.

You can add support for drag and drop to all Flex components. Flex also includes built-in support for the drag-and-drop operation for certain controls such as List, Tree, and DataGrid, that automate much of the processing required to support drag and drop.

The drag-and-drop operation has three main stages: initiation, dragging, and dropping:

Initiation

User initiates a drag-and-drop operation by using the mouse to select a Flex component, or an item in a Flex component, and then moving the component or item while holding down the mouse button. For example, a user selects an item in a List control with the mouse and, while holding down the mouse button, moves the mouse several pixels. The selected component, the List control in this example, is the drag initiator.

Dragging

While still holding down the mouse button, the user moves the mouse around the Flex application. Flex displays an image during the drag, called the drag proxy. A drag source object (an object of type DragSource) contains the data being dragged.

Dropping

When the user moves the drag proxy over another Flex component, that component becomes a possible drop target. The drop target inspects the drag source object to determine whether the data is in a format that the target accepts and, if so, allows the user to drop the data onto it. If the drop target determines that the data is not in an acceptable format, the drop target disallows the drop.

A drag-and-drop operation either copies or moves data from the drag initiator to the drop target. Upon a successful drop, Flex adds the data to the drop target and, optionally, deletes it from the drag initiator in the case of a move.

A single Flex component can function as both the drag initiator and the drop target. This lets you move the data within the component.

You can specify the List control as both the drag initiator and the drop target, you can use drag and drop to rearrange the items in the control. For example, if you use a Canvas container as the drag initiator and the drop target, you can then use drag and drop to move controls in the Canvas container to rearrange them.

Drag and drop is event driven. To configure a component as a drag initiator or as a drop target, you have to write event handlers for specific events, such as the dragDrop and dragEnter events.

The following controls include built-in support for the drag-and-drop operation:

The built-in support for these controls lets you move items by dragging them from a drag-enabled control to a drop-enabled control. However, to copy items, you must add additional logic.

For all list classes except the Tree control, the default value of the dragMoveEnabled property is false, so you can only copy elements from one control to the other. By setting the dragMoveEnabled to true in the first List control, you can move and copy data. For the Tree control, the default value of the dragMoveEnabled property is true.

When the dragMoveEnabled property is set to true, the default drag-and-drop action is to move the drag data. To perform a copy, hold down the Control key during the drag-and-drop operation.

The only requirement on the drag and drop operation is that the structure of the data providers must match for the two controls. In this example, the data provider for srclist is an Array of Strings, and the data provider for the destination List control is an empty Array. If the data provider for destlist is an Array of some other type of data, destlist might not display the dragged data correctly.

You can modify the dragged data as part of a drag-and-drop operation to make the dragged data compatible with the destination.


You can use drag and drop to copy data between two different types of controls, or between controls that use different data formats. To handle this situation, you write an event handler for the dragDrop event that converts the data from the format of the drag initiator to the format required by the drop target.


Drag and drop properties for list-based controls

List-based controls provide properties and methods for managing the drag-and-drop operation. The following table lists these properties and methods:

Property/Method

Description

dropIndicatorSkin

Specifies the name of the skin to use for the drop-insert indicator which shows where the dragged data will be inserted.

The default value is ListDropIndicator.

dragEnabled

A Boolean value that specifies whether the control is a drag initiator. The default value is false. When true, users can drag selected items from the control. When a user drags items from the control, Flex creates a DragSource object that contains the following data objects:

  • A copy of the selected item or items in the control.
    For all controls except for Tree, the format string is "items" and the items implement the IDataProvider interface.
    For Tree controls the format string is "treeItems" and the items implement the ITreeDataProvider API interface.
  • A copy of the initiator, with a format String of "source".
dropEnabled

A Boolean value that specifies whether the control can be a drop target that uses default values for handling items dropped onto it. The default value is false, which means that you must write event handlers for the drag events. When the value is true, you can drop items onto the control by using the default drop behavior.

When you set dropEnabled to true, Flex automatically calls the showDropFeedback() and hideDropFeedback() methods to display the drop indicator.

dragMoveEnabled

If the value is true, and the dragEnabled property is true, specifies that you can move or copy items from the drag initiator to the drop target. When you move an item, the item is deleted from the drag initiator when you add it to the drop target.

If the value is false, you can only copy an item to the drop target. For a copy, the item in the drag initiator is not affected by the drop.

When the dragMoveEnabled property is true, you must hold down the Control key during the drop operation to perform a copy.

The default value is false for all list controls except the Tree control, and true for the Tree control.

calculateDropIndex

Returns the item index in the drop target where the item will be dropped. Used by the dragDrop event handler to add the items in the correct location.

Not available in the TileList or HorizontalList controls.

hideDropFeedback()

Hides drop target feedback and removes the focus rectangle from the target. You typically call this method from within the handler for the dragExit and dragDrop events.

showDropFeedback()

Specifies to display the focus rectangle around the target control and positions the drop indicator where the drop operation should occur. If the control has active scroll bars, hovering the mouse pointer over the control's top or bottom scrolls the contents.

You typically call this method from within the handler for the dragOver event.



Monday, April 27, 2009

AdvancedDataGrid control

The AdvancedDataGrid control expands on the functionality of the standard DataGrid control to add data visualization capabilities to your Adobe® Flex™ application.

The following table describes the main data visualization capabilities of the AdvancedDataGrid control:

Capability

Description

Sorting by multiple columns

Sort by multiple columns when you click in the column header. For more information, see Sorting by multiple columns.

Styling rows and columns

Use the styleFunction property to specify a function to apply styles to rows and columns of the control. For more information, see Styling rows and columns.

Displaying hierarchical and grouped data

Use an expandable navigation tree in a column to control the visible rows of the control. For more information, see Hierarchical and grouped data display.

Creating column groups

Collect multiple columns under a single column heading. For more information, see Creating column groups.

Using item renderers

Span multiple columns with an item renderer and use multiple item renderers in the same column. For more information, see Using item renderers with the AdvancedDataGrid control.



To disable sorting for an entire AdvancedDataGrid control, set the AdvancedDataGrid.sortableColumns property to false. To disable sorting for an individual column, set the AdvancedDataGridColumn.sortable property to false.

The way that you sort multiple columns is based on the setting of the sortExpertMode property. By default, the sortExpertMode property is set to false. This setting means that you click in the header area of a column to sort the rows of the AdvancedDataGrid control by that column. Then you click in the multiple column sort area of the header to sort by additional columns. To use the Control key to select every column after the first column to perform sort, set the sortExpertMode property to true.

DataGrid control

The DataGrid control is like a List except that it can show more than one column of data making it suited for showing objects with multiple properties.

The DataGrid control provides the following features:

  • Columns of different widths or identical fixed widths
  • Columns that the user can resize at runtime
  • Columns that the user can reorder at runtime
  • Optional customizable column headers
  • Ability to use a custom item renderer for any column to display data other than text
  • Support for sorting the data by clicking on a column
The DataGrid control is intended for viewing data.

Difference between ButtonBar and ToggleButtonBar controls

The ButtonBar control defines group of buttons that do not retain a selected state. When you select a button in a ButtonBar control, the button changes its appearance to the selected state; when you release the button, it returns to the deselected state.

The ToggleButtonBar control defines a group buttons that maintain their state, either selected or deselected. Only one button in the ToggleButtonBar control can be in the selected state. That means when you select a button in a ToggleButtonBar control, the button stays in the selected state until you select a different button.

The ButtonBar and ToggleButtonBar controls define a horizontal or vertical row of related buttons with a common appearance. The controls define a single event, the itemClick event, that is dispatched when any button in the control is selected.

Create view states

The base view state of an application or component is the default view state. If you omit any view state specifications, you can consider your application to have a singe view state: the base state.

To add additional view states to the base view state, you use the
tag. Within the body of the tag, you can add one or more tags, one for each additional view state.

The UIComponent class defines the currentState property that you use to set the view state. When the application starts, the default value of the currentState property is ' '.

An application or component can set the initial view state to a non-base view state. To use a view state other than the base state as the initial view state, set the currentState property to the specific view.

ControlBar Layout Container

You use the ControlBar container with a Panel or TitleWindow container to hold components that can be shared by the other children in the Panel or TitleWindow container.

About forms

Flex supports form development by using the Form layout container and several child components of the Form container. The Form container lets you control the layout of a form, mark form fields as required or optional, handle error messages, and bind your form data to the Flex data model to perform data checking and validation. Also, you can apply style sheets to configure the appearance of your forms.

Saturday, April 25, 2009

View states

In many rich Internet applications, the interface changes based on the task the user is performing. A simple example is an image that changes when the user rolls the mouse over it or changing from a browse view to a detail view. View states let you easily implement such applications.

A view state defines a particular view of a component.

To create a view state, you define a base state, and then define a set of changes, or overrides, that modify the base state to define the new view state. Each additional view state can modify the base state by adding or removing child components, by setting style and property values, or by defining state-specific event handlers.

A view state does not have to modify the base

Events

Events let a developer know when something happens within a Flex application. They can be generated by user devices, such as the mouse and keyboard, or other external input, such as the return of a web service call. Events are also triggered when changes happen in the appearance or life cycle of a component, such as the creation or destruction of a component or when the component is resized.

You can "handle" these events in your code by adding an event handler. Event handlers are the functions or methods that you write to respond to specific events. They are also sometimes referred to as event listeners.

Components generate and dispatch events and consume (listen to) other events.

An object that requires information about another object's events registers a listener with that object. When an event occurs, the object dispatches the event to all registered listeners by calling a function that was requested during registration. To receive multiple events from the same object, you must register your listener for each event.

All visual objects, including Flex controls and containers, are subclasses of the DisplayObject class. They are in a tree of visible objects that make up your application. The root of the tree is the Stage. Below that is the SystemManager object, and then the Application object. Child containers and components are leaf nodes of the tree. That tree is known as the display list. An object on the display list is analogous to a node in the DOM hierarchical structure. The terms display list object and node are used interchangeably.



Associative arrays with object keys


You can use the Dictionary class to create an associative array that uses objects for keys rather than strings. Such arrays are sometimes called dictionaries, hashes, or maps.

import flash.display.Sprite;
import flash.utils.Dictionary;
var groupMap:Dictionary = new Dictionary();

// objects to use as keys
var spr1:Sprite = new Sprite();
var spr2:Sprite = new Sprite();
var spr3:Sprite = new Sprite();

// objects to use as values
var groupA:Object = new Object();
var groupB:Object = new Object();

// Create new key-value pairs in dictionary.

groupMap[spr1] = groupA;
groupMap[spr2] = groupB;

how to create associative arrays that use strings for keys

There are two ways to create associative arrays in ActionScript 3.0.

The first way is to use the Object constructor, which has the advantage of allowing you to initialize your array with an object literal.

An instance of the Object class, also called a generic object, is functionally identical to an associative array. Each property name of the generic object serves as the key that provides access to a stored value.

The following example creates an associative array named monitorInfo, using an object literal to initialize the array with two key and value pairs:

var monitorInfo:Object = {type:"Flat Panel", resolution:"1600 x 1200"};

trace(monitorInfo["type"], monitorInfo["resolution"]);
// output: Flat Panel 1600 x 1200

If you do not need to initialize the array at declaration time, you can use the Object constructor to create the array, as follows:

var monitorInfo:Object = new Object();

After the array is created using either an object literal or the Object class constructor, you can add new values to the array using either the bracket operator ([]) or the dot operator (.). The following example adds two new values to monitorArray:

monitorInfo["aspect ratio"] = "16:10";
monitorInfo.colors = "16.7 million";
trace(monitorInfo["aspect ratio"], monitorInfo.colors);
// output: 16:10 16.7 million

The second way to create an associative array is to use the Array constructor (or the constructor of any dynamic class) and then use either the bracket operator ([]) or the dot operator (.) to add key and value pairs to the array. If you declare your associative array to be of type Array, you cannot use an object literal to initialize the array. The following example creates an associative array named monitorInfo using the Array constructor and adds a key called type and a key called resolution, along with their values:

var monitorInfo:Array = new Array(); monitorInfo["type"] = "Flat Panel"; monitorInfo["resolution"] = "1600 x 1200"; trace(monitorInfo["type"], monitorInfo["resolution"]); // output: Flat Panel 1600 x 1200

There is no advantage in using the Array constructor to create an associative array. You cannot use the Array.length property or any of the methods of the Array class with associative arrays, even if you use the Array constructor or the Array data type. The use of the Array constructor is best left for the creation of indexed arrays.



Associative arrays

An associative array, sometimes called a hash or map, uses keys instead of a numeric index to organize stored values. Each key in an associative array is a unique string that is used to access a stored value.

An associative array is an instance of the Object class, which means that each key corresponds to a property name. Associative arrays are unordered collections of key and value pairs.

ActionScript 3.0 introduces an advanced type of associative array called a dictionary.

Dictionaries, which are instances of the Dictionary class in the flash.utils package, use keys that can be of any data type but are usually instances of the Object class. In other words, dictionary keys are not limited to values of type String.


Sort and Query/manipulate an array

Sorting an array

There are three methods--reverse(), sort(), and sortOn()--that allow you to change the order of an array, either by sorting or reversing the order. All of these methods modify the existing array.

The reverse() method changes the order of the array such that the last element becomes the first element, the penultimate element becomes the second element, and so on.

The sort() method allows you to sort an array in a variety of predefined ways, and even allows you to create custom sorting algorithms.

The sortOn() method allows you to sort an indexed array of objects that have one or more common properties that can be used as sort keys.

Querying an array

The four methods of the Array class--concat(), join(), slice(), toString()--all query the array for information, but do not modify the array.

The concat() and slice() methods both return new arrays, while the join() and toString() methods both return strings.

The concat() method takes a new array or list of elements as arguments and combines it with the existing array to create a new array.

The slice() method has two parameters, aptly named startIndex and an endIndex, and returns a new array containing a copy of the elements "sliced" from the existing array. The slice begins with the element at startIndex and ends with the element just before endIndex. That bears repeating: the element at endIndex is not included in the return value.


You can use the join() and toString() methods to query the array and return its contents as a string. If no parameters are used for the join() method, the two methods behave identically--they return a string containing a comma-delimited list of all elements in the array.

The join() method, unlike the toString() method, accepts a parameter named delimiter, which allows you to choose the symbol to use as a separator between each element in the returned string.

How to remove array elements

Three methods of the Array class--pop(), shift(), and splice()--allow you to remove elements from an array.

The pop() method removes an element from the end of the array. In other words, it removes the element at the highest index number.

The shift() method removes an element from the beginning of the array, which means that it always removes the element at index number 0.

The splice() method, which can also be used to insert elements, removes an arbitrary number of elements starting at the index number specified by the first argument sent to the method.

How to insert array elements

Three of the Array class methods--push(), unshift(), and splice()--allow you to insert elements into an array.

The push() method appends one or more elements to the end of an array. In other words, the last element inserted into the array using the push() method will have the highest index number.

The unshift() method inserts one or more elements at the beginning of an array, which is always at index number 0.

The splice() method will insert any number of items at a specified index in the array.

Arrays

ARRAYS:

Array: An object that serves as a container to group multiple objects together.

Associative array: An array that uses string keys to identify individual elements.

Dictionary: An array whose items consist of pairs of objects, known as the key and the value. The key is used instead of a numeric index to identify a single element.

Element: A single item in an array.

Index: The numeric "address" used to identify a single element in an indexed array.

Indexed array: The standard type of array that stores each element in a numbered element, and uses the number (index) to identify individual elements.

Key: The string or object used to identify a single element in an associative array or a dictionary.

Multidimensional array: An array containing items that are arrays rather than single values.