June 17, 2008
itemEditors - Part 3
The previous article in this series discussed item editing events. Using events can make your application respond to what the user enters and help the user make fewer mistakes.
This article is about using itemRenderers as itemEditors - one class to do both display data and edit the data. I tend to think of it more as an itemEditor used as an itemRenderer. But that's just me.
Download source for these examples.
Further, I have to be honest and say I am not a big fan of the renderer-as-editor; I think renderers should present data and editors should edit it. There are a few occasions when I think it is a good idea to use a single class for both, but those times are very few in my opinion.
Examples
Here is an example of over-using the itemRendererAsEditor. The DataGrid on the left is a nice, clean DataGrid. All of the cells are editable and when you click or tab into a cell its editor appears. The DataGrid on the right uses itemEditors to render the cells and edit them. All you see are the editors: TextInput controls for some columns, a ComboBox for another, and a NumericStepper for the last. Lots going on, very busy to look at.
![]() |
![]() |
| itemEditors only | itemRenderers as itemEditors |
Here is an example of using the CheckBox as both an itemRenderer and an itemEditor. I think the CheckBox works really well for this. It is clean, simple control and you can readily see whether a value is true or false. Plus you can just click it to change it. Straightforward implementation, good user experience.

Here is another example of using an itemEditor as a renderer. This List control represents a shopping cart. In it are all of the things you have added to your cart while shopping online at your favorite grocery store.

As you can see, the quantity of each item in the cart is represented by a NumericStepper. All the user has to do is change the quantity and the cart is updated. A delete button would also be a good idea here, too.
Shopping Cart
This complex editor/renderer class works as follows:
<?xml version="1.0" encoding="utf-8"?>
<mx:HBox xmlns:mx="http://www.adobe.com/2006/mxml" verticalAlign="middle" paddingRight="4" paddingLeft="4" >
<mx:Script>
<![CDATA[
public function get quantity() : Number
{
return itemQuantity.value;
}
]]>
</mx:Script>
<mx:CurrencyFormatter id="cfmt" precision="2" />
<mx:Label text="{data.name}" fontWeight="bold" fontSize="12"/>
<mx:Spacer width="100%"/>
<mx:NumericStepper id="itemQuantity" value="{data.quantity}"
minimum="0"
maximum="100"/>
<mx:Label text="{cfmt.format(data.price*itemQuantity.value)}" width="66"/>
</mx:HBox>
As with every itemEditor, this one has a property used as the editorDataField. In this case it is the quantity property getter function. The function retrieves the value setting of the NumericStepper (with id itemQuantity).
As an itemRenderer, this component must also display the current quantity (as well as the product name, price, and sub-total). These values are displayed through data binding. The sub-total is actually an ActionScript expression, multiplying the price by the value of the NumericStepper. As the NumericStepper is changed so does the sub-total.
Now you are probably wondering how to get the grand total below the shopping cart to update as the NumericSteppers are changed. Simply changing the sub-total and the quantity field of the itemRenderer/Editor will not update the grand total. Remember that the editor does not commit the new value into the data provider until after the edit completes. In other words, if you increase the value of the NumericStepper for the Snow Peas row, the grand total will not update until focus leaves the Snow Peas row. This is so you can validate the information as shown in previous articles.
For a shopping cart like this, you want the grand total to update as the user changes the NumericSteppers. So you have to force the situation a little.
The first thing you do is have the itemRenderer class implment the IDropInListItemRenderer interface. This gives you access to the listData which contains a reference to the list itself and, through that, to the dataProvider.
The code demonstrating this is available in the download. Look for the ShoppingCartRendererExtra.mxml file.
Once you have the listData you can have the change event on the NumericStepper force an update on the dataProvider:
private function forceUpdate() : void
{
// Access the collection - listData.owner is the List and from there you have its dataProvider.
var ac:ArrayCollection = (listData.owner as List).dataProvider as ArrayCollection;
// update the quantity field from the numeric stepper. This is what the List will automatically
// do when editing completes, but since you want to see the grand total change as the NumericStepper
// changes, you have to force things a bit.
data.quantity = itemQuantity.value;
// finally, tell the collection the data changed. this will cause the collection to
// dispatch its own change event which is then picked up by the main application.
ac.itemUpdated(data);
}
When the NumericStepper's change event triggers this event handler, the ArrayCollection has the item updated immediately, rather than waiting for the List to complete editing the cell. If the main application is listening for a COLLECTION_CHANGE event on the collection, the grand total can be calculated:
<mx:ArrayCollection id="shoppingCartDB"
source="{shoppingCartArray}"
collectionChange="updateCartTotal()" />
...
private function updateCartTotal() : void
{
if( cartTotal ) {
var total:Number = 0;
for(var i:int=0; i < shoppingCartDB.length; i++)
{
var record:Object = shoppingCartDB.getItemAt(i);
total += record.price * record.quantity;
}
cartTotal.text = cfmt.format(total);
}
}
Conclusion
Take care when turning an itemRenderer into an itemEditor. The user should have a straightforward interface with a single purpose when editing a cell or record. I personally prefer to separate the functions, but there are times when using an itemRenderer as an itemEditor can make sense, even if you have to go the extra mile as with this shopping cart grand total example.
Posted by pent at 12:22 PM | Comments (4)
June 04, 2008
itemEditors - Part Two
Editing Events and Complex Editors
In the last article of this series you saw how to make some simple inline itemEditors. If you have read the series on itemRenderers, then you noticed how similar the two are.
The key to making an itemEditor work is a) naming the class using the itemEditor property and b) naming the value property of the itemEditor using the editorDataField property.
In this article I'll show you how to use events to do some simple data validation and to prevent certain cells from being edited. In the course of this you will see how to make more complex itemEditors.
A word of caution here: by "complex" I do not mean editors with many controls and layouts. I really mean slightly more complex than inline itemEditors. The reason being is that I think it is unfair to ask users to make complex edits within a list or cell of a DataGrid. An editor should be focused only one one thing: the contents of a cell. For example, if you are using the List control and presenting a shopping cart, it is not unreasonable to allow the user to change the quantity of the items in the cart by letting them edit that value right in the cell. What would be unreasonable is to allow them to change the item itself, the colors, quantity, special instructions, and so forth. Or in other words, allow them to shop for items right from the cart when you have a whole site that does that. The cart is just a checkout convenience. Sure, let them add an extra tub of ice cream or delete a bag of chips, but don't have them turn the bag of chips into a two boxes of whole wheat pasta.
The itemEditEnd event
Let's say you have a DataGrid which helps you mange inventory. One of things you can do is change part numbers, but you cannot allow a part number to be blank. Using the default itemEditor, the TextInput control, you can click on a cell in the "Part #" column, press the delete key and erase the part number. This is one technique to prevent that.
<mx:DataGrid x="10" y="64" editable="true" dataProvider="{inventoryDB}"
itemEditEnd="verifyInput(event)">
<mx:columns>
<mx:DataGridColumn headerText="Product" dataField="product"/>
<mx:DataGridColumn headerText="Part #" dataField="part"/>
<mx:DataGridColumn headerText="Type" dataField="type"
itemEditor="editors.ProductTypeEditor" editorDataField="type"/>
<mx:DataGridColumn headerText="Quantity" dataField="quantity"/>
</mx:columns>
</mx:DataGrid>
The list controls dispatch an itemEditEnd event whenever editing is about to be completed. The event happens before the data is commited back to the dataProvider. By handling this event you have the option of changing the data, validating the data, and stopping the commit if necessary. For this example, the verifyInput() function will make sure the product part number is not empty.
private function verifyInput( event:DataGridEvent ) : void
{
// it is OK if the user cancels the edit
if( event.reason == DataGridEventReason.CANCELLED ) return;
// grab the instance of the itemEditor. For this DataGrid, only the
// TextInput control is used as the editor, so it is safe to get the
// editor no matter what column has been edited.
var editor:TextInput = (event.currentTarget as DataGrid).itemEditorInstance as TextInput;
// if the edit is on the part number column, make sure it is not blank
if( event.dataField == "part" )
{
if( editor.text.length == 0 ) {
// call event.preventDefault() so the edit will not continue and store the
// blank value
event.preventDefault();
// give the editor an error to display to the user
editor.errorString = "You must enter a part number";
return;
}
}
// handle other columns here
}
The event is a DataGridEvent and contains some very useful properties. The reason property tells you why the event was dispatched. If the user pressed the ESCAPE key or clicked outside of the DataGrid the reason will be DataGridEventReason.CANCELLED. You may want to ignore this event as I have done and just let the DataGrid to its default action which is to cancel the edit and restore the previous value.
If you have decided to handle the event then you will need the itemEditor to get to its properties. The event's currentTarget property contains the control which I have cast to DataGrid. The DataGrid has an itemEditorInstance property which I cast to TextInput which is the type of itemEditor for this example.
This event handler is called for any cell so you must determine if the edit is something you are interested in pursuing. I check the event's dataField property to make sure it is the "part" column. If so, I test the editor's text property to see if there are any characters in it. If there are no characters, two things happen:
First: the event.preventDefault() is called. This is how to prevent the edit from happening - prevent the DataGrid from storing the new value back into the dataProvider. For the user, they will have pressed TAB or ENTER and nothing will appear to happen. The preventDefault() function will keep the itemEditor in place.
Second: I put an errorString onto the TextInput control. This is optional, but it does signal the user that there is something wrong. Afterall, they pressed the TAB or ENTER key and nothing happened.
The itemEditBeginning Event
There are times you might want to prevent a cell from being edited. You could set the DataGridColumn's editable property to false, but that prevents every cell from being edited. Suppose you just want to make some of the cells in the column uneditable? You can determine whether a cell is editable or not using the itemEditBeginning event.
<mx:DataGrid x="10" y="64" editable="true" dataProvider="{inventoryDB}"
itemEditEnd="verifyInput(event)"
itemEditBeginning="allowForEdit(event)">
<mx:columns>
<mx:DataGridColumn headerText="Product" dataField="product"/>
<mx:DataGridColumn headerText="Part #" dataField="part"/>
<mx:DataGridColumn headerText="Type" dataField="type"
itemEditor="editors.ProductTypeEditor" editorDataField="type"/>
<mx:DataGridColumn headerText="Quantity" dataField="quantity"/>
</mx:columns>
</mx:DataGrid>
Handling the itemEditBeginning event gives you the option of dynamically deciding the editability of a cell. In this example, the data has a field called permanent on each record. The idea is that permanent=true means the product name is an unchangable value so the product cell for that row cannot be edited. This is handled by the allowForEdit() function:
private function allowForEdit(event:DataGridEvent) : void
{
// if the field to be edited is a product, prevent the user from making
// changes if the permanent flag is true<. You can use more complex logic,
// of course.
if( event.dataField == "product" ) {
var item:Object = ((event.currentTarget as DataGrid).dataProvider as ArrayCollection)[event.rowIndex];
if( item.permanent ) {
event.preventDefault();
}
}
// handle other columns here
}
Again, the event is a DataGridEvent and here I have checked the dataField property of the event to make sure it is the "product" field I am dealing with. I can then get the record from the dataProvider of the DataGrid using the currentTarget property of the event and cast that to DataGrid. I then cast the DataGrid's dataProvider to ArrayCollection and get the event.rowIndex value. I could also have used the inventoryDB ArrayCollection directly in this function since they are in the same file, but this is more generic.
Once I have the record I can query its permanent property and if it is true, call the event.preventDefault() function to disable editing of that cell. In the case, the default behavior of itemEditBeginning is to present the itemEditor; preventing the default behavior makes the cell uneditable.
Editing Limitations
While I was proof reading this article I thought of something you might try and do and offer a warning. When you are using these edit events and trying to determine if the event should proceed, you may be tempted to make a call to a backend or server process. For example, you may have a web service where you can validate a part number. You may be tempted, while inside of the itemEditEnd event, to make a web service call and validate what the user just entered. Seems logical, right?
Logical maybe, but it won't work. The reason is that data service calls are asynchronous. You can make the call, sure, but the result will be returned sometime later - well after your event handler has exited. In fact, your call won't actually be made until your function exits. Your call is queued and when the Flex framework exits the function the request will be made and then the result will be returned by your web service's result handler.
So there is no way to do this type of server-side validation while editing cells. You should query the server, when your application starts, for the data to validate against, then use that while the cells are being edited.
Conclusion
The ability to dynamically allow editing and to validate the edit is a excellent way to give your users a better experience. You can help them make fewer mistakes and give feedback during the editing process. You can prevent them from editing certain data and make it easier for yourself to write the application since you do not have to validate what the user cannot change.
In next article I'll cover itemRenderers used as itemEditors.
Posted by pent at 01:15 PM | Comments (1)
May 29, 2008
itemEditors - Part 1
inline itemEditors
I recently completed a series on itemRenderers - customizations to list controls which format the display of the list contents. Displaying and rendering content is very cool and with Flex you can do nearly anything you can imagine.
This new series covers itemEditors - a way to allow data to be changed directly inside of a list control. This first article covers inline itemEditors which are very simple, though quite useful, components you write directly inside your MXML files. The other articles in the series will cover more complex editing, validation, events, and using itemRenderers as itemEditors.
The source code to this article is available by downloading it here.
TextInput Editor
It is nice to edit directly in the list controls. You can imagine a DataGrid of warehouse inventory where you can adjust the content right in the grid without needing a special pop-up. The list controls have a built in editor - a TextInput control - which appears whenever the user clicks the mouse in an editable area, either a row (for a List), a branch (for a Tree), or a cell (for a DataGrid). All you need to do is set the list control's editable property to true. For a DataGrid you can exclude a column from being edited by setting the DataGridColumn's editable property to false.
![]() |
![]() |
Before editing a cell |
After clicking on a cell, the editor opens and the content is ready for editing. |
itemEditors differ from itemRenderers in that only one instance of the itemEditor is seen - just on the cell being edited. The itemEditor is not seen until the cell to be edited receives input focus. Then the itemRenderer is hidden and the itemEditor is moved to that position, sized to fit the area, and given the data for the record. When editing is finished (by moving focus to another location), the list control copies the new value from the editor to the dataProvider record.
Using the image above as an example, when the user clicks in a cell of the "Part #" column, the dataProvider[row][dataField] value is given to the text property of the itemEditor (TextInput) control. When editing is finished, the text property value from the itemEditor (TextInput) control is copied to the dataProvider[row][dataField]. The dataProvider, being a collection, dispatches an event in response to the update.
While the default TextInput control makes a fine editor, it really only works for the most simple of cases. It works fine for String values, for example, such as a book title, author name, or product number. If you need more control or want to validate the user's input, then you need to take matter into your own hands.
Flex Controls as itemEditors
Here is how you make an itemEditor which only accepts numeric values:
<mx:DataGrid x="46" y="270" editable="true" dataProvider="{employeeDB}">
<mx:columns>
<mx:DataGridColumn headerText="Name" dataField="name"/>
<mx:DataGridColumn headerText="Position" dataField="position"/>
<mx:DataGridColumn headerText="Age" dataField="age">
<mx:itemEditor>
<mx:Component>
<mx:TextInput restrict="0-9" maxChars="3" />
</mx:Component>
</mx:itemEditor>
</mx:DataGridColumn>
</mx:columns>
</mx:DataGrid>
A very common control to use for an itemEditor is the CheckBox. This is very useful for editing Boolean values. Here is an example of using the CheckBox to edit the values for an "In Stock" column of an inventory program:

<mx:DataGrid x="531" y="273" editable="true" dataProvider="{inventoryDB}">
<mx:columns>
<mx:DataGridColumn headerText="Product" dataField="product"/>
<mx:DataGridColumn headerText="Part #" dataField="part"/>
<mx:DataGridColumn headerText="In Stock?" dataField="inStock"
labelFunction="inStockLabeler"
itemEditor="mx.controls.CheckBox" editorDataField="selected" />
<mx:DataGridColumn headerText="Quantity" dataField="quantity"/>
</mx:columns>
</mx:DataGrid>
In this example the content of the cells in this column are rendered using a labelFunction (inStockLabeler) which could display anything such as "Yes", "No", "In Stock", or "Out of Stock". The itemEditor property is set to the mx.controls.CheckBox class. And there is another, equally important, property set on the DataGridColumn: editorDataField. This field indicates the property of the itemEditor class to use to fetch the value when editing is finished. In this case it is the CheckBox's selected property. When editing is finished, the DataGrid will use the CheckBox's selected property to replace the inStock property in the data record.
You may wonder why the example with the TextInput did not supply the editorDataField property. That is because the default value for editorDataField is "text" which just happens to be name of the property on the TextInput control holding the value.
You can use this same technique with a number of Flex controls. Here is one for an order quantity column using NumericStepper:

<mx:DataGrid x="531" y="82" editable="true" dataProvider="{inventoryDB}">
<mx:columns>
<mx:DataGridColumn headerText="Product" dataField="product"/>
<mx:DataGridColumn headerText="Part #" dataField="part"/>
<mx:DataGridColumn headerText="In Stock?" dataField="inStock"/>
<mx:DataGridColumn headerText="Quantity" dataField="quantity"
itemEditor="mx.controls.NumericStepper" editorDataField="value"/>
</mx:columns>
</mx:DataGrid>
Notice the editorDataField is "value" - the property of the NumericStepper which holds the current value of the control. Make sure you use the fully-qualified class name for the itemEditor property.
Complex Editor
Now suppose you want to do something a little more complex that doesn't have a ready-made Flex control available. Here is one which allows a credit card number to be entered using 4 separate 4-digit fields:

<mx:DataGrid x="46" y="463" editable="true" dataProvider="{accountDB}" width="302">
<mx:columns>
<mx:DataGridColumn headerText="Account" dataField="account" width="100"/>
<mx:DataGridColumn headerText="Credit Card" dataField="ccard" editorDataField="value">
<mx:itemEditor>
<mx:Component>
<mx:HBox>
<mx:Script>
<![CDATA[
public function get value() : String
{
return part1.text+part2.text+part3.text+part4.text;
}
override public function set data(value:Object):void
{
super.data = value;
part1.text = value.ccard.substr(0,4);
part2.text = value.ccard.substr(4,4);
part3.text = value.ccard.substr(8,4);
part4.text = value.ccard.substr(12,4);
}
]]>
</mx:Script>
<mx:TextInput id="part1" maxChars="4" restrict="[0-9]" width="40" />
<mx:TextInput id="part2" maxChars="4" restrict="[0-9]" width="40" />
<mx:TextInput id="part3" maxChars="4" restrict="[0-9]" width="40" />
<mx:TextInput id="part4" maxChars="4" restrict="[0-9]" width="40" />
</mx:HBox>
</mx:Component>
</mx:itemEditor>
</mx:DataGridColumn>
</mx:columns>
</mx:DataGrid>
This inline itemEditor follows the same rules as other itemEditors and names the editorDataField as "value". The component chosen for the itemEditor is the HBox - which does not have a "value" property. To make this itemEditor work, a getter function named value is created to return the concatenation of the 4 input fields. Now when editing for the cell completes, the DataGrid can call upon the value property of the itemEditor and it will receive the combined fields.
You can also see that I have overridden the data setter function. In that function I split up the credit card number among the four TextInput fields. This is the technique you use to display the data to be edited. The editorDataField is the property used to retrieve the new value.
Conclusion
In this article you've seen how to create an inline itemEditor - from simply naming a class to creating a complex class right within the MXML tags. By naming the property of the editor class which contains the final editor value, the DataGrid can retreive the value from the editor instance and replace the current value in the data.
The next article covers more complex itemEditors and editing events.
Posted by pent at 05:39 PM | Comments (5)
April 02, 2008
itemRenderers: Part 5: Efficiency
If you are displaying a large number of itemRenderers - either in the DataGrid or AdvancedDataGrid - your application's performance may be adversely affected if you do not code these itemRenderers effeciently. Here are some tips that might help:
- Limit the number of columns using itemRenderers. Do you really need to have every column be a custom itemRenderer? Sometimes you do, but is all that glitz overwhelming the user?
- Try not to change the style of the elements in your itemRenderer too frequenty. If you need to switch styles (eg, green for positive values, red for negative values), consider having 2 controls preset with those styles and making one visible. Changing styles is one of the more time-consuming tasks in Flex.
- Do not use Containers as the basis for your itemRenderers. Containers have a lot of overhead. They are fine for limited use, but it would be more efficient to write your itemRenderers based on UIComponent.
Switching Styles
Here's an itemRenderer which switches components depending on the value of the data field.
<mx:Canvas>
<mx:Script><![CDATA
private function lessThanZero() : Boolean {
return data.price < 0;
}
]]></mx:Script>
<mx:Label text="{data.price}" color="#FF0000" visible="{lessThanZero()}" />
<mx:Label text="{data.price}" color="#00FF00" visible="{!lessThanZero()}" />
</mx:Canvas>
This will be faster than setting the style. Some other things to keep in mind:
- Avoid data binding to styles. Not only is changing styles slower than most operations, adding data binding code on top of it just makes it worse.
- Use a Canvas or extend ListItemRenderer or as the root of the itemRenderer. This allows you to place controls on top of each other.
Extending UIComponent
By far the most efficient way to write an itemRenderer is to extend UIComponent using an ActionScript class. You'll have complete control of the code and the renderer will be as efficient as possible.
Let's start with the example above, switching styles, and write a simple itemRenderer extending UIComponent.
package renderers
{
import mx.controls.listClasses.IListItemRenderer;
import mx.core.UIComponent;
public class PriceItemRenderer extends UIComponent implements IListItemRenderer
{
public function PriceItemRenderer()
{
super();
}
}
}
You'll notice that not only did I write the class to extend UIComponent, I also have it implementing the IListItemRenderer interface. It is necessary to do this because a list control will expect any renderer to implement this interface and if you do not, you'll get a runtime error as the list attempts to cast the renderer to this interface.
If you read the documentation on IListItemRenderer you'll see that is an amalgamation of many other interfaces, most of which UIComponent implements for you. But there is one interface extended by IListItemRenderer that UIComponent does not implement: IDataRenderer. This requires you to add the code to give the itemRenderer class the data property you've been using all along.
If you attempt to use this class without implementing IDataRenderer you'll get these errors when you compile the code:
1044: Interface method get data in namespace mx.core:IDataRenderer not implemented by class renderers:PriceItemRenderer.
1044: Interface method set data in namespace mx.core:IDataRenderer not implemented by class renderers:PriceItemRenderer.
Edit this class and change it to the following:
package renderers
{
import mx.controls.listClasses.IListItemRenderer;
import mx.core.UIComponent;
import mx.events.FlexEvent;
public class PriceItemRenderer extends UIComponent implements IListItemRenderer
{
public function PriceItemRenderer()
{
super();
}
// Internal variable for the property value.
private var _data:Object;
// Make the data property bindable.
[Bindable("dataChange")]
// Define the getter method.
public function get data():Object {
return _data;
}
// Define the setter method, and dispatch an event when the property
// changes to support data binding.
public function set data(value:Object):void {
_data = value;
dispatchEvent(new FlexEvent(FlexEvent.DATA_CHANGE));
}
}
}
I took the code directly from the Flex documentation for IDataRenderer, so you don't even have to type it yourself.
With that out of the way we can add in the two labels.
- Add variables to hold the two labels.
private var posLabel:Label; private var negLabel:Label;
- Modify the set data function to call invalidateProperties(). This is important because the change of the data has to make the text in the labels change AND to change their visibility.
public function set data(value:Object):void { _data = value; invalidateProperties(); dispatchEvent(new FlexEvent(FlexEvent.DATA_CHANGE)); }Calling invalidateProperties() tells the Flex framework to call the commitProperties() function at the apppriate time. - Override createChildren() and create the labels, adding them to the display list of the component.
Notice that in addition to creating the labels, their styles and visible are also set.
override protected function createChildren() : void { super.createChildren(); posLabel = new Label(); posLabel.visible = false; posLabel.setStyle("color", 0x00FF00); addChild(posLabel); negLabel = new Label(); negLabel.visible = false; negLabel.setStyle("color", 0xFF0000); addChild(negLabel); } - Override commitProperties() to set the labels' text and visibility.
In the past you've been overriding set data to make this type of change, and you can do that in this class, too, if you prefer.
override protected function commitProperties():void { super.commitProperties(); posLabel.text = data.price; negLabel.text = data.price; posLabel.visible = Number(data.price) > 0; negLabel.visible = Number(data.price) < 0; } - Override updateDisplayList() to size and position the labels.
You must size the labels because their default size is 0x0. This is another thing a Container class will do for you. Since this is a pretty simple itemRenderer you can just set the labels' size to match the size of the itemRenderer.
override protected function updateDisplayList( unscaledWidth:Number, unscaledHeight:Number ) : void { super.updateDisplayList(unscaledWidth, unscaledHeight); posLabel.move(0,0); posLabel.setActualSize(unscaledWidth,unscaledHeight); negLabel.move(0,0); negLabel.setActualSize(unscaledWidth, unscaledHeight); }
All this probably seems a bit complicated just to do this, but keep in mind that using a container will add a lot more code than this.
UIComponent Notes
The UIComponent class is the basis for all visual Flex components - controls and containers. Here are some tips about using UIComponent as your itemRenderer.
- UIComponent imposes no layout restrictions on its children (unlike a Container). You have to position and size the children yourself.
- It is also possible to draw graphics and position children beyond the size specified in updateDisplayList().
- If you plan on using variableRowHeight in your list, you should also override the measure() function to give the list an idea of how big the itemRenderer is.
- To use UIComponent as an itemRenderer you must implement IDataRenderer.
- To use the listData property you must implement IDropInListItemRenderer; that was covered in a previous article of this series.
Posted by pent at 11:50 AM | Comments (11)
March 27, 2008
itemRenderers: Part 4: States and Transitions
Communicating the with the user of your application is what your itemRenderer does best. Sometimes that communication is as simple as presenting a name; sometimes more elborately using colors; and sometimes with interactivity.
itemEditors are truely interactive controls, but they are not the focus of this article. In these examples we'll look at itemRenderers that change their visual appearance based on either the data itself or the user's actions.
States
The Flex <mx:State> is a very good way to change the appearance of an itemRenderer. States are easy to use, and when combined with Transitions, give the user feedback and pleasent experience.
In this example we'll create a new MXML itemRenderer (and remember, you can do this completely in ActionScript if you prefer) for the List. All this shows is the image, title, author, price, and a Button to purchase the book.
<?xml version="1.0" encoding="utf-8"?>
<mx:HBox xmlns:mx="http://www.adobe.com/2006/mxml" >
<mx:Image id="bookImage" source="{data.image}" />
<mx:VBox height="115" width="100%" verticalAlign="top" verticalGap="0" paddingRight="10">
<mx:Text text="{data.title}" fontWeight="bold" width="100%"/>
<mx:Label text="{data.author}" />
<mx:HBox id="priceBox" width="100%">
<mx:Label text="{data.price}" width="100%"/>
<mx:Button label="Buy" />
</mx:HBox>
</mx:VBox>
</mx:HBox>
What we want however, is if the book is not in stock (the data has <instock> nodes which are either yes or no) for the price and Book to be invisible. I've made things a bit convenient for myself here because I gave the HBox parent of the price and Button an id. This allows me to change the visibility of both of those items by changing the visibility of the HBox, priceBox.
You can do this by overridding the set data function, which we'll do, but instead of directly changing the visibility of priceBox, we'll use this state defintion:
<mx:states>
<mx:State name="NoStockState">
<mx:SetProperty target="{priceBox}" name="visible" value="false"/>
</mx:State>
</mx:states>
Place this just below the root tag.
This example is a bit far-fetched in that it is overly complicated to do a simple task, but it shows how to use states. There are 2 states:
- The base state - this is the normal state of a component. Components that do not use states simply have this base state. In this example, the base state has the priceBox visible property as true (the default). This is the case when instock is "yes".
- The NoStockState - this is the state when the value of nostock is "no". When this state is active the SetProperty instructions are carried out. The target determines which member of the class is in question, the name property is the name of the property to change on the target, and value is the new value for the property.
The set data function determines which state to use by looking at the value of instock:
override public function set data( value:Object ) : void
{
super.data = value;
if( data )
{
if( data.instock == "yes" )
currentState = "";
else
currentState = "NoStockState";
}
}
The currentState is a property of all UIComponent controls. It determines which State is the active one. When switching between states the Flex framework begins with the base state and then applies the rules for the given state.
Remember that itemRenderers are recycled, so you must always restore values; never leave an if without an else in an itemRenderer.
If you are feeling adventurous, you can do away with the set data override in this example. Instead, set currentState directly in the root tag by using data binding expression:
<mx:HBox xmlns:mx="http://www.adobe.com/2006/mxml" width="400"
currentState="{data.instock == 'yes' ? '' : 'NoStockState'}" >
The currentState's value is set by examining data.instock right inline with the root tag. A nice trick, but it might be harder to maintain.
Adding Elements
In this itemRenderer the price and Buy button appears only if the instack value is yes. You could do this without a state of course, but if your itemRenderer has more controls to be added or removed, a state will make more sense as their appearance is controlled simply by setting the itemRenderer's currentState property.
Instead of just removing the price and Button, we'll have the state add a label telling the user the item is out of stock. Here's the modified state:
<mx:states>
<mx:State name="NoStockState">
<mx:SetProperty target="{priceBox}" name="visible" value="false"/>
<mx:AddChild relativeTo="{priceBox}" position="before">
<mx:Label text="-- currently not in stock --" color="#73DAF0"/>
</mx:AddChild>
</mx:State>
</mx:states>
The <mx:AddChild> tag says to add the Label into the priceBox. In addition to setting the priceBox's visible property to false, a friendly message replaces it.
Again, you could add this label in the set data function - or add it initially and just set its visibility to false and change it to true in the set data function. But I think you can see the value of the State: if the requirement for the instock being no condition gets more complex, all you need to do is adjust the NoStockState; the ActionScript code which switches the state remains the same.
You can modify states in Flex Builder's Design View.
Expanding List
This example does not work well for list controls but does perform nicely for a VBox and Repeater. This question of expanding an item in place becomes dicy when the list has to be scrolled. Imagine this: you've got a list of items will all the same height. Now you exand the height of item 2. So far so good - item 2 is taller than the other visible items. And there's the catch: the visible items. Now scroll the list. Remember that itemRenderers are recycled. So when item 2 scrolls out of view, its itemRenderer will be moved to the bottom of the list. You've got to reset its height. OK, that can work pretty simply. Now scroll the list so item 2 is back in view. You would expect it to be the expanded height. How does the itemRenderer know to do that? From previous articles you know that information either comes from the data itself or from some external source.
I think a resizing itemRenderer is too complex and not really worth the effort. I believe there is a better way to do this using VBox and Repeater. However, the catch with Repeater is that every child will be created. If you have 1,000 records and use a Repeater you will get 1,000 instances of your itemRenderer.
For this example you'll still write an itemRenderer but will use it as the child of a VBox. The elements of a list look pretty simple: the name of a book and its author. But click the itemRenderer and it expands in place. This is accomplished using:
- The itemRenderer has a state which includes the additional information.
- The itemRenderer uses a Resize transition to give a smoother expansion and contraction of the itemRenderer.
The base state of the itemRenderer is pretty simple:
<mx:HBox width="100%">
<mx:Label text="{data.author}" fontWeight="bold"/>
<mx:Text text="{data.title}" width="100%" fontSize="12" selectable="false"/>
</mx:HBox>
The ExpandedState adds the additional elements which contribute to the itemRenderer's height:
<mx:states>
<mx:State name="ExpandedState">
<mx:AddChild position="lastChild">
<mx:HBox width="100%">
<mx:Image source="{data.image}"/>
<mx:Spacer width="100%"/>
<mx:Label text="{data.price}"/>
<mx:Button label="Buy"/>
</mx:HBox>
</mx:AddChild>
</mx:State>
</mx:states>
Getting the itemRenderer to change size is as simple as adding a Transition:
<mx:transitions>
<mx:Transition fromState="*" toState="*">
<mx:Resize target="{this}" />
</mx:Transition>
</mx:transitions>
Place this below the <mx:states>
The Transition is applied whenever the state changes because its fromState and toState properties are wildcards. Now all you have to do is add event handler for clicking on the itemRenderer (add a click event to the root tag) and change the state:
<mx:Script>
<![CDATA[
private function expandItem() : void
{
if( currentState == "ExpandedState" )
currentState = "";
else
currentState = "ExpandedState";
}
]]>
</mx:Script>
Summary
States are a great way to make a number of modifications to the visual appearance of the itemRenderer. You can group the changes in a State and simply make it all happen by setting the currentState property of the itemRenderer.
In the next article we'll look at writing more efficient itemRenderers by extending UIComponent.
Posted by pent at 04:22 PM | Comments (1)
March 03, 2008
itemRenderers: Part 1: inline renderers
I'm starting a new series of articles on itemRenderers. Our documentation team has great examples so please check that information out first. I'm giving you my distillation of it.
Recycling Renderers
One thing many people try to do is access an itemRenderer from outside of the list. For example, you might want to make the cell in the 4th column of the 5th row in a DataGrid turn green because you've just received new data from the server. Getting that itemRenderer instance and modifying it externally would be a huge breech of the Flex framework and component model.
To understand itemRenderers you have to understand why they are what they are and what our intentions were when we designed them. BTW - when I say 'we' I really mean the Adobe Flex engineering team - I had nothing to do with it. Anyway, suppose you have 1000 records you want to show. If you think the list control creates 1000 itemRenderers you are incorrect. If the list is showing only 10 rows, the list creates about 12 itemRenderers - enough to show every visible row plus a couple for buffering and performance reasons. The list initially shows rows 1 through 10. When the user scrolls the list it may now be showing rows 3 - 12. But those same 12 itemRenderers are still there - no new itemRenderers were created, even after the list scrolled.
Here's what we do. When the list is scrolled, those itemRenderers which will still be showing the same data (rows 3 - 10) are moved upward. Aside from being in a new location, they haven't changed. The itemRenderers that were showing the data for rows 1 and 2 are now moved below the itemRenderer for row 10. Then those itemRenderers are given the data for rows 11 and 12. In other words, unless you resize the list, those same itemRenderers are reused - recycled - to a new location and are now showing new data.
If you want to change the background color of the cell in the 4th column of the 5th row, be aware that the itemRenderer for that cell may now be showing the contents of the 21st row if the user has scrolled the list.
So how do you make changes like this?
The itemRenderers must change themselves based on the data they are given to show. If the itemRenderer for the list is supposed to change its color based on a value of the data, then it must look at the data it is given and change itself.
inline itemRenderers
In this article we'll look at the answer to this problem using inline itemRenderers. An inline itemRenderer is one which is written directly in the MXML file where the list control occurs. In the next article we'll look at writing external itemRenderers. The inline itemRenderers are the least complex and are generally used for very simple renderers or for prototyping a larger application. There's nothing wrong with inline itemRenderers, but when the code becomes complex it is better to extract it into its own class.
In all of the examples we'll use the same data: a collection of information about books: author, title, publication date, thumbnail image, and so forth. Each record is an XML node which looks like this:
<book>
<author>Peter F. Hamilton</author>
<title>Pandora's Star</title>
<image>assets/pandoras_star_.jpg</image>
<date>Dec 3, 2004</date>
</book>
Let's start with a simple itemRenderer using a <mx:List> control. Here, the author is listed followed by the title of the book.
<mx:List x="29" y="67" dataProvider="{testData.book}" width="286" height="190">
<mx:itemRenderer>
<mx:Component>
<mx:Label text="{data.author}: {data.title}" />
</mx:Component>
</mx:itemRenderer>
</mx:List>
This itemRenderer is so simple that a labelFunction would probably have been better, but it at least lets you focus on the important parts. First, an inline itemRenderer uses the <mx:itemRenderer> tag to define it. Within this tag is the <mx:Component> tag. This tag must be here as it tells the Flex complier you are defining a component inline. We'll discuss what this really means in a bit.
Within the <mx:Component> tag you define your itemRenderer. For this example it is a single <mx:Label> with its text field set to a data-binding expression: {data.author}: {data.title}. This is very important. The list control gives each itemRenderer instance the record of the dataProvider by setting the itemRenderer's data property. Looking at the code above, it means that for any given row of the list, the itemRenderer instance of its inline itemRenderer will have its data property set to a <book> XML node (such as the one above). As you scroll through the list, the data property is being changed as the itemRenderers are recycled for new rows.
In other words, the itemRenderer instance for row 1 might have its data.author set to "Peter F. Hamilton" now, but when it scrolls out of view, the itemRenderer will be recycled and the data property - for that same itemRenderer - may now have its data.author set to "J.K. Rowling". All of this happens automatically as the list scrolls - you don't worry about it.
Here's a more complex inline itemRenderer using the <mx:List> control again:
<mx:List x="372" y="67" width="351" height="190" variableRowHeight="true" dataProvider="{testData.book}">
<mx:itemRenderer>
<mx:Component>
<mx:HBox >
<mx:Image source="{data.image}" width="50" height="50" scaleContent="true" />
<mx:Label text="{data.author}" width="125" />
<mx:Text text="{data.title}" width="100%" />
</mx:HBox>
</mx:Component>
</mx:itemRenderer>
</mx:List>
This really isn't much different. Instead of a <mx:Label> the itemRenderer is an <mx:HBox> with an <mx:Image>, <mx:Label>, and a <mx:Text> control. Data-binding still relates the visual with the record.
DataGrid
You can use inline itemRenderers on a DataGrid, too. Here's one applied to a column:
<mx:DataGrid x="29" y="303" width="694" height="190" dataProvider="{testData.book}" variableRowHeight="true">
<mx:columns>
<mx:DataGridColumn headerText="Pub Date" dataField="date" width="85" />
<mx:DataGridColumn headerText="Author" dataField="author" width="125"/>
<mx:DataGridColumn headerText="Title" dataField="title">
<mx:itemRenderer>
<mx:Component>
<mx:HBox paddingLeft="2">
<mx:Script>
<![CDATA[
override public function set data( value:Object ) : void {
super.data = value;
var today:Number = (new Date()).time;
var pubDate:Number = Date.parse(data.date);
if( pubDate > today ) setStyle("backgroundColor",0xff99ff);
else setStyle("backgroundColor",0xffffff);
}
]]>
</mx:Script>
<mx:Image source="{data.image}" width="50" height="50" scaleContent="true" />
<mx:Text width="100%" text="{data.title}" />
</mx:HBox>
</mx:Component>
</mx:itemRenderer>
</mx:DataGridColumn>
</mx:columns>
</mx:DataGrid>
As you can see, this is much more complex than the last two, but it has the same structure: <mx:itemRenderer> with <mx:Component> definition inside of it.
The purpose of <mx:Component> is to provide an MXML syntax for creating an ActionScript class right in the code. Picture the code that appears in the <mx:Component> block being cut out and put into a separate file and given a class name. When you look at the inline itemRenderer it does look like a complete MXML file, doesn't it? There's the root tag (<mx:HBox> in this case) and even a <mx:Script> block.
The purpose of the <mx:Script> block in this example is to override the set data function so the background color of the itemRenderer can be changed. In this case, the background is changed from white whenever the publication data for a book is in the future. Remember that itemRenderers are recycled, so the color must also be set back to white if the test fails. Otherwise all of the itemRenderers will eventually turn purple as the user scrolls through the list.
outerDocument
The scope has also changed. What I mean is, variables that you define from within a <mx:Component> are only scoped to that component/inline itemRenderer. Likewise, the content outside of the <mx:Component> is in a different scope, just as if this component were defined in a separate file. For instance, suppose you add a Button to this itemRenderer that allows the user to by the book from an online retailer. Buttons call functions on their click event, so you might define the button like this:
<mx:Button label="Buy" click="buyBook(data)" />
If the buyBook() function were defined in the <mx:Script> block of the file you would get an error saying that buyBook() is an undefined method. That's because buyBook() is defined in the scope of the file, not in the scope of the <mx:Component>. Since this is a typical use case there is a way around that using the outerDocument identifier:
<mx:Button label="Buy" click="outerDocument.buyBook(data)" />
The outerDocument identifier changes the scope to look into the file, or outer document, with reference to the <mx:Component>. Now beware: the function has to be a public function, not a protected or private one. Remember that <mx:Component> is treated as an externally defined class.
Bubbling Events
Let's look at another, even more complex example. This is a TileList using the same data.
<mx:TileList x="29" y="542" width="694" dataProvider="{testData.book}" height="232" columnWidth="275" rowHeight="135" >
<mx:itemRenderer>
<mx:Component>
<mx:HBox verticalAlign="top">
<mx:Image source="{data.image}" />
<mx:VBox height="115" verticalAlign="top" verticalGap="0">
<mx:Text text="{data.title}" fontWeight="bold" width="100%"/>
<mx:Spacer height="20" />
<mx:Label text="{data.author}" />
<mx:Label text="Available {data.date}" />
<mx:Spacer height="100%" />
<mx:HBox width="100%" horizontalAlign="right">
<mx:Button label="Buy" fillColors="[0x99ff99,0x99ff99]">
<mx:click>
<![CDATA[
var e:BuyBookEvent = new BuyBookEvent();
e.bookData = data;
dispatchEvent(e);
]]>
</mx:click>
</mx:Button>
</mx:HBox>
</mx:VBox>
</mx:HBox>
</mx:Component>
</mx:itemRenderer>
</mx:TileList>
The itemRenderer looks like this when the application is run:

This itemRenderer is pretty close to the one used in the DataGrid, but the Buy button's click event doesn't use outerDocument to call a function. In this case the click event creates a custom event which bubbles up out of the itemRenderer, through the TileList, and is received by some higher component in the visual chain.
This is a very common problem: you have an itemRenderer which has some interactive control in it, usually a Button, LinkButton, etc. that is supposed to cause some action to take place when clicked. Perhaps it is to delete the row or in this case, buy the book.
It is unreasonable to expect the itemRenderer to do the work. Afterall, the itemRenderer's job is to make the list look good - period. Event bubbling allows the itemRenderer to pass off the work to something else. A custom event is useful here because the event is related to the data on the row - so why not include that data in the event; the receiver of the event won't have to go hunt it down.
Summary
Using inline itemRenderers is a great and quick way to give your lists a custom look. Consider inline itemRenderers as separate ActionScript classes - afterall, they are scoped as if they were. If you must refer to functions or properties in the containing file, use the outerDocument identifier to change the scope. If you need to communicate information as the result of an interaction with the itemRenderer, use a custom, bubbling, event.
And remember: don't try to get hold of itemRenderers - they are recycled for a purpose. Make them responsible only to the data given to them.
In the next article I'll discuss external itemRenderers.
Posted by pent at 08:26 AM | Comments (11)
February 29, 2008
Migrating from Flex 2 to Flex 3
Check this link before migrating your applications from Flex 2 to Flex 3. In my own experience the issues have been very minor and fixed within a few minutes. But your results will varying depending on what controls you've used and how large your application is.
http://learn.adobe.com/wiki/display/Flex/Backwards+Compatibility+Issues
Posted by pent at 12:05 PM
December 31, 2007
Scrolling Text Component
Here's another example of a Flex component. This one scrolls a message within a fixed area. The message can be scrolled vertically or horizontally. You can give it a try right here:
This component shows how to use custom properties, meta data to work with Flex Builder, and overriding functions.
Click here to download the source code. The download is a Flex Builder 3 Beta 3 project - if you do not have Flex Builder 3 Beta 3 from Adobe Labs, you can open the file as a regular archive and use the source code.
Posted by pent at 08:27 AM | Comments (15)
December 24, 2007
Component Pack from ILOG
I've been asked a number of times if there are more chart types, as well as other controls, available for Flex. Perhaps I'm late to the party, but I just came across this announcement (from October 2007) that Adobe and ILOG are teaming up to enhance Flex 3.
Here's a quick list of what's available in the ILOG ELIXR package. You can find out more on Adobe Labs: http://labs.adobe.com/wiki/index.php/Flex_3:ILOG
- Radar charts (also named spider charts)
- Full 3D charts including bar/column, area, line and pie
- Treemap component, for analyzing large data sets
- Scheduling component, allowing users to view and manipulate time series data
- Organizational charts
- Country maps for creating interactive reports or dashboards
Posted by pent at 11:07 AM | Comments (1)
December 20, 2007
Component Class - Part Five
The last article in this series showed how to write the CycleSelectButton from scratch. In this article I'll look at styling and skinning the component.
Skins versus Styles
One frequently asked question is "what's the difference between styles and skins?" This is a good question and it is confusing a bit because you specify a component's skins using specific styles on the component. For example, the upSkin style on the Button component.
Styles control the appearance of a component while skins are the appearence. Or put another way, skins use styles to present the component. Take the borderColor style. It's purpose is to specify the color of a component's edge. The component's skin can use that style to draw its border - which may be round or square, thick or thin (using the borderThickness style). The skin contains the look of the component.
The reason skins are specified as style is so you can build an entire look or theme using just style sheets (.CSS files). If skins were specified in ActionScript you would have to deliver a new SWF for each theme. Having the skins and other styles in CSS means you can change the theme of an application with a new style sheet.
There are two types of skins: graphical and programmatic. Graphical skins are bitmaps: GIFs, JPGs, PNGs, etc. In Flex 3 you can import graphical skins from Adobe Illustrator and Adobe Photoshop. You can use Adobe Flash CS3 to create animated skins (picture a button that pulses with color).
Programmatic skins are written in ActionScript. They are class files that usually extend mx.skins.ProgrammaticSkin which is a very lightweight class. The class uses its override of updateDisplayList() to render the skin using the drawing API (see flash.display.Graphics).
Each component has its own set of skins. For a Button there are 8 possible skins: upSkin (its normal state), overSkin (when the mouse hovers over it), downSkin (when the mouse is pressed over it), disabledSkin (when the Button's enabled property is false), selectedUpSkin (when the Button's toggle property is true), selectedOverSkin (toggle is true and mouse is hovering over the Button), selectedDownSkin (toggle is true and mouse is pressed over it), and selectedDisabledSkin (toggle is true and enabled is false). If you want to use graphical skins for a Button, you should supply 8 different image files. If your Button will never be a toggle, then you can supply just 4 skins.
Download Example
This is a zip file and contains a full Flex Builder 3 project. You will either need Flex Builder 3 from Adobe Labs or you can use Flex Builder 2 and import the sources into a project. This project contains the source from the previous articles as well.
If you decide to use a programmatic skin you can either make separate skin classes, or use a single class, or a combination. A programmatic skin can detect which skin style it is being used for and code within the programmatic skin class can adjust for it. If, for example, the skin class is being used for a Button's upSkin, overSkin, downSkin, and disabledSkin, the class can decide to draw a green-filled circle for the upSkin, a blue-filled circle for the overSkin, a blue-filled circle for the downSkin, and a gray-filled circle for the disabledSkin.
You decide what works best for the look you want. You can wind up with a collection of skins - both graphical and programmatic - that make your application look unique (or follow your company's user interface guidelines).
Applying Skins
Applying the skins is simple. I prefer to do it in a style-sheet to make them easier to change:
Button {
upSkin: Embed('assets/BlueButtonUp.gif');
overSkin: Embed(source='assets/CompanyIcons.swf',symbol='GreenButton');
downSkin: ClassReference('com.mycompany.skins.StandardButtonSkin');
disabledSkin: ClassReference('com.mycompany.skins.StandardButtonSkin');
}
This pretty wild Button has a mixture of skins: one is a GIF, another is a symbol out of a SWF, and two come from the same ActionScript class.
Specifying a graphical skin uses the Embed directive. For a simple image file the Embed names the file using a path that is relative to the application's main file, or an absolute path within the project. The example above uses a relative path. When a Flash SWF is used, the skin can be the entire SWF file or a specific symbol within the SWF. If you chose to use a specific symbol, the Embed directive names the file and the symbol within it.
Specifying a programmatic skin uses the ClassReference directive. The full class name, including its package, is given for the reference. The compiler will find that class and pull it into the SWF.
The main advantage of programmatic skins over graphical skins is scaling. Because programmatic skins use the Flash Drawing API, the skins scale and rotate very well. Graphical skins can easily become distorted unless you scale9grid specifications in the Embed directive. The scale9grid specifications let you specify a grid overlay on the graphic that tells the Flash Player which parts of the graphic to scale. Think of a rectangle where you want the 4 corners to never scale, the top and bottom to scale only when the graphic is stretched horizontally, the left and right edges to scale when the graphic is stretched vertically, and the center to always scale.
Going back to the CycleSelectButton component, here is how the createChildren() function looks currently:
override protected function createChildren() : void
{
arrows = new Arrows();
arrows.width = 20;
arrows.height= 20;
addChild(arrows);
linkButton = new LinkButton();
addChild(linkButton);
// add a listener for the click on the LinkButton.
linkButton.addEventListener(MouseEvent.CLICK, handleClick);
super.createChildren();
}
To redo this component using skins, you have to think about which parts of the component should be skinable. It seems like a good idea for the circle of arrows to be a skin. Maybe you want to make your own arrows using Photoshop, for instance.
Here is the modified createChildren() function that introduces skins:
var skin:Class;
skin = getStyle("arrowSkin");
if( skin == null ) skin = CycleSelectArrowSkin;
_arrowSkin = new skin();
_arrowSkin.name = "arrowSkin";
if( _arrowSkin is ProgrammaticSkin ) (_arrowSkin as ProgrammaticSkin).styleName = this;
_arrowSkin.width = 20;
_arrowSkin.height= 20;
addChild(_arrowSkin as DisplayObject);
This is a bit different. First, the value for the arrowSkin style is retrieved. The arrowSkin style is specified by metadata above the class declaration:
[Style(name="arrowSkin",type="Class",inherit="yes")]
Notice that the type of the style data is "Class" - you want to load the class definition for the skin, not just the name of the class. This works for Embed as well since a class is created from the embedded image data.
If no arrowSkin style has been specified, then the default class, CycleSelectArrowSkin, is given. Then the arrowSkin member variable is set with a new instance of whatever skin class was selected. This is the standard way to specify skins using styles.
Once the class instance has been created and arrowSkin is now set, you'll see it is given a name ("arrowSkin") and its style is set to this. What it means is that the skin will get all of the styles set on the component. For example, the CycleSelectArrowSkin uses a style called "arrowColor" to draw the arrow graphic. There isn't any way from outside of the CycleSelectButton code to associate this style with the arrow skin; the style is set on the component, along with the arrowSkin style shown above:
[Style(name="arrowColor",type="Number",format="Color",inherit="yes")] [Style(name="arrowSkin",type="Class",inherit="yes")]
With the skin inheriting the component's style, arrowColor among them, the skin code can draw the arrows.
Details
In this section I go through the steps in more detail . I'll use the sample CycleSelectButton available from the download with this article, but I will only show the skin for the arrows; the skins for the rest of the component work the same way and it will be less confusing to focus on one skin.
Step 1: Figure out what you want the skin to be used for. In this case, it is for the cycle of arrows and by making it a skin, gives a developer the chance to change the look of the component without re-writing the component.
Step 2: In the component class file (CycleSelectButton.as), define the style for the skin above the class definition:
[Style(name="arrowSkin",type="Class",inherit="yes")]
public class CycleSelectButton extends UIComponent
{
Make sure the type of the style is "Class". The name will be used in the style sheet or on the MXML tag for the component:
StyleSheet.css:
CycleSelectButton {
arrowSkin: ClassReference('com.adobe.examples.skins.CycleSelectArrowSkin');
or
arrowSkin: Embed('assets/ArrowSkin.png');
}
MXML:
<buttons:CycleSelectButton arrowSkin="com.adobe.examples.skins.CycleSelectArrowSkin"... />
or
<buttons:CycleSelectButton arrowSkin="@Embed('assets/ArrowSkin.png')" ... />
Step 3: Declare a member variable to hold the skin instance:
private var _arrowSkin:IFlexDisplayObject;
Notice that the type of the variable is IFlexDisplayObject - not CycleSelectArrow skin, not UIComponent, and not even ProgrammaticSkin. If you want your skin to be either a programmatic skin or a graphic skin, you need to use a data type that is common to both. IFlexDisplayObject fills that need. It is generic enough, but also allows you to position and size the skin.
Step 4: Create the skin. You can do this either in createChildren() or in commitProperties().
var skin:Class;
skin = getStyle("arrowSkin");
if( skin == null ) skin = CycleSelectArrowSkin;
_arrowSkin = new skin();
_arrowSkin.name = "arrowSkin";
if( _arrowSkin is ProgrammaticSkin ) (_arrowSkin as ProgrammaticSkin).styleName = this;
_arrowSkin.width = 20;
_arrowSkin.height= 20;
addChild(_arrowSkin as DisplayObject);
The getStyle() function is used to get an alternative skin class (ProgrammaticSkin or graphic) from the styles for the component. This is how a custom skin can be used from a style sheet or MXML tag (from Step 2 above). If no skin was specified getStyle() returns null. In this case a default skin is used. It is important that when using skins you are consistent and create a default skin; creating a skin as a default is always a good idea and perhaps it too can be extended and customized.
Once the skin class is chosen, the arrowSkin member (from Step 3) is set with an instance of this class. Now it is either a graphic skin or a ProgrammaticSkin. If the latter you must set the styleName of the skin to be this (or some other object instance which holds the styles). If you don't do this, the ProgrammaticSkin will fail when it uses getStyle().
You can size the skin at this step IF you know the size. If your skin is going to occupy the entire component's space, you can set it within updateDisplayList() (see Step 5).
Finally you add the skin as a child of the component. Note that you have to cast the skin as a DisplayObject since addChild does not accept IFlexDisplayObject parameters.
Step 5: Position (and optionally, size) the skin in updateDisplayList():
override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void
{
super.updateDisplayList( unscaledWidth, unscaledHeight );
// position the arrowSkin
_arrowSkin.move( 10,10 );
Here the arrowSkin is moved into position. If you were to have a skin that required it to be sized, then you can do that too using skin.setActualSize( width, height ) where the width and height might be unscaledWidth, unscaledHeight or some derivative of those values.
That's all you need to do to use a skin in your component. Notice that none of the component's look has been done by the actual component code - it is all done by the skin. This gives your component a tremendous amount of flexability in how it is presented, not in how it behaves.
The Skin Itself
The CycleSelectArrowSkin is one of the files available in the download with this article. Here are some of the highlights:
public class CycleSelectArrowSkin extends ProgrammaticSkin
The class extends mx.skins.ProgrammaticSkin which extends flash.display.Shape. That's because skins should be very light-weight and be limited to just presenting graphics. However, one of the most powerful properties of Flex and the Flash Player is its flexability. You do not have to make your skins extend ProgrammaticSkin. You can use any class which implements the IFlexDisplayObject interface.
Since skins are so lightweight there isn't much else they do except override updateDisplayList():
override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void
{
super.updateDisplayList( unscaledWidth, unscaledHeight );
var color:Number;
switch( name )
{
case "arrowSkin":
color = getStyle("arrowColor");
if( isNaN(color) ) color = getStyle("themeColor");
break;
case "arrowDisabledSkin":
color = 0xAAAAAA;
break;
}
drawArrows( graphics, color );
}
In this function, the skin's name is used to determine its color. If the skin is the "arrowSkin" then the color is extracted from the "arrowColor" style. If that was not defined, then the skin's color defaults to the "themeColor".
Using the themeColor as a default - whether it is the actual color or a darker or lighter version (see mx.utils.ColorUtil class) - is a good idea since that color flows nicely with the style sheet and theme idea.
Once the color is chosen the skin is drawn. The drawArrows function is the same as it was before:
private function drawArrows( g:Graphics, color:uint ) : void
{
g.clear();
g.lineStyle(0, color, 1);
g.moveTo(-10,0);
g.curveTo(-10,-10,0,-10);
g.curveTo(2.5,-11,8,-8);
g.moveTo(8,-8);
g.lineTo(6.5,-13);
g.moveTo(8,-8);
g.lineTo(2.5,-6);
g.moveTo(10,0);
g.curveTo(10,10,0,10);
g.curveTo(-2.5,11,-8,8);
g.moveTo(-8,8);
g.lineTo(-6.5,13);
g.moveTo(-8,8);
g.lineTo(-2.5,6);
}
Summary
That's all there is to skinning components:
- Figure out what you want to skin,
- extract the drawing into a class based on ProgrammaticSkin,
- add the skin as a style to your component,
- create an instance of the skin, and position it.
You should now be able to make reusable components for all of your Flex projects.
Posted by pent at 02:35 AM | Comments (4)
December 13, 2007
Flex 3 Beta 3 Available
The third and final public beta releases of Flex 3 and Adobe AIR are now available for download on Adobe labs. These releases are focused on quality and performance, resolving numerous bugs from beta 2. This is your final chance to provide feedback on the release before launch, so please take this opportunity to take a final, thorough look. You can download the final beta releases of Flex 3, Flex Builder 3, and Adobe AIR on Adobe Labs at: http://labs.adobe.com/. Please also be sure to check out BlazeDS, the newest open source Remoting and Messaging project from Adobe.
Posted by pent at 08:20 AM
November 29, 2007
PopUp, Can You Hear Me?
Communicating with a PopUp is a common task. This article explores how to do that.
The first example shows how to use Alert to pose a question and get answer.
private function showQuestion() : void
{
Alert.show("Do you like Flex?", "Question", Alert.YES|Alert.NO,this,processAnswer);
}
private function processAnswer( event:CloseEvent ) : void
{
if( event.detail == Alert.YES ) {
response.text = "Of course you do!";
} else {
response.text = "Hmm. Really? Keep reading then.";
}
}
Now that you've seen how Alert works, let's look at a more complex example. Here, a TitleWindow is used to present a choice of themes (you can see one like it in my Atmospheres AIR Music Player). When the user picks the Apply button the theme changes.
This is the code for the pop-up, ThemeChooser.mxml:
<?xml version="1.0" encoding="utf-8"?>
<mx:TitleWindow xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical"
width="338" height="252"
title="Choose Your Theme"
showCloseButton="true"
horizontalAlign="center"
verticalAlign="middle"
close="PopUpManager.removePopUp(this)">
<mx:Metadata>
[Event(name="changeTheme", type="theme.ThemeEvent")]
</mx:Metadata>
<mx:Script>
<![CDATA[
import theme.ThemeEvent;
import mx.managers.PopUpManager;
private function dispatchThemeChoice( themeName:String ) : void
{
dispatchEvent( new ThemeEvent(themeName) );
PopUpManager.removePopUp(this);
}
]]>
</mx:Script>
<mx:VBox horizontalAlign="left" verticalGap="17">
<mx:RadioButton label="Adobe Red" click="dispatchThemeChoice('adobeRed')"/>
<mx:RadioButton label="Orange Neon" click="dispatchThemeChoice('orangeNeon')"/>
<mx:RadioButton label="Blue Wave" click="dispatchThemeChoice('blueWave')"/>
</mx:VBox>
</mx:TitleWindow>
Notice that when a RadioButton is clicked, an event is dispatched. The event is a
ThemeEvent - a custom event type. This is the code for the event, ThemeEvent.as:
package theme
{
import flash.events.Event;
public class ThemeEvent extends Event
{
public static const CHANGE_THEME:String = "changeTheme";
public function ThemeEvent(themeName:String, bubbles:Boolean=false, cancelable:Boolean=false)
{
super(CHANGE_THEME, bubbles, cancelable);
this.themeName = themeName;
}
public var themeName:String;
}
}
This is the code for the main application to demonstrate it:
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" height="271" width="532"
borderStyle="solid"
borderColor="black"
borderThickness="1">
<mx:Script>
<![CDATA[
import theme.ThemeEvent;
import theme.ThemeChooser;
import mx.managers.PopUpManager;
import mx.core.IFlexDisplayObject;
private function showThemeDialog() : void
{
var pop:IFlexDisplayObject = PopUpManager.createPopUp(this, theme.ThemeChooser, true );
pop.addEventListener( ThemeEvent.CHANGE_THEME, selectTheme );
PopUpManager.centerPopUp(pop);
result.text = ""; // reset
}
private function selectTheme( event:ThemeEvent ) : void
{
result.text = event.themeName;
}
]]>
</mx:Script>
<mx:Button x="24" y="27" label="Select Theme" click="showThemeDialog()"/>
<mx:Label x="24" y="57" fontWeight="bold" color="#FFFFFF" id="result"/>
</mx:Application>
I think this is the easiest solution: a custom event. The event contains all of the information from the pop-up and lets the pop-up disappear without having to hang around while you get information from it. If you have a lot of data (e.g., a user's profile) consider creating a class to represent it and have the custom event contain an instance of the class. This also makes it easier to change the information later.
Both of these examples use window-type classes as the base for the pop-ups. But you can use any component for a pop-up. Here's a pop-up that's a shape with text; it has no buttons nor a frame. Click it make it go away. While not very intuitive, it does make the point.
Download Files
You can download the code for this specialized pop-up here.This zip file is a Flex Builder 3, Beta 2, project archive. If you do have Flex Builder 3, Beta 2, you can import the source files directly from the zip.
When you use a modal pop-up, which is what all these examples have been so far, you'll notice that the background becomes lighter and blurred. This is governed by styles on the Application which you can change. You can change the color and amount of blur. You can even get rid of both.
Mode-less pop-ups are common as floating tool bars. There's no difference in how you make them nor interact with them, just in how you present them. Using a mode-less pop-up enables the user to continue working with the application while the pop-up is still present.
I hope this gives you some ideas in case you need to pop-up dialogs or warnings. Be unconvential and use events to communicate the result of the pop-up back to the main application.
Posted by pent at 11:52 AM | Comments (0)
October 31, 2007
Component Class - Part Four
In the previous article in this series you saw how the Arrow part of the CycleSelectButton was created. In this article we'll write the CycleSelectButton from scratch by extending UIComponent. Watch how similar this component's construction is to the V2 and Arrows components.
Start by creating a new ActionScript class and call it
CycleSelectButtonV3 . Have it extend
UIComponent :
public class CycleSelectButtonV3 extends UIComponent
{
/**
* constructor function
*
* This is a good place to set inital styles
*/
public function CycleSelectButtonV3()
{
super();
}
To make this simple for you - and to drive home the point of how similar things are - copy the following items from the V2 component into this V3 component:
- The
[Event]metadata; - the linkButton and arrows variable definitions (be sure to copy the import statements, too);
- the
createChildren()function; - The
dataProviderproperty set and get functions; - The
selectedIndexproperty set and get functions; - The
commitProperties()function; - The
handleClick()event handler function.
So what's left? I'm not sure all of that will compile, but give it a try and if it does, put it into a Flex application and test it out. Not quite right, huh?
This zip file contains the source for this component and a sample application.
The V2 version of this component extends HBox which does a couple of things for you: it handles the placement or layout of the component. By using HBox you don't have to worry about how big things are and where they go. HBox always measures each child and sticks one after the other.
Since this V3 component extends UIComponent you don't have any of that help. You have to implement a couple of the Flex framework functions to make the component behave correctly.
measure()
Look back at the Arrows component and you'll see two things that are missing from this V3 component: the
measure() and
updateDisplayList() functions. Measure() is important because the Flex framework needs to know how big the component is in order to position it within a container. The updateDisplayList() function is important to position the arrows and linkButton - something HBox did for you.
override protected function measure() : void
{
super.measure();
measuredWidth = arrows.getExplicitOrMeasuredWidth() + linkButton.getExplicitOrMeasuredWidth();
measuredHeight= Math.max( arrows.getExplicitOrMeasuredHeight(), linkButton.getExplicitOrMeasuredHeight() );
}
The measure() function must set the
measuredWidth and
measuredHeight properties. Since the component's design is to be horizontal with the arrows followed by the linkButton, the width is then the sum of each child's width. The height is the largest of the two.
If your component is also given an explicit width and height, then this measure() method will not be called.
Noticed the call to
getExplicitOrMeasuredWidth (and
getExplicitOrMeasuredHeight ). Since the arrows child has been given a size of 20x20, these functions return the explicit size of 20. The linkButton however, was not given a size, so it has to be measured.
updateDisplayList()
Once the child components have been measured and an overall size for the component has been determined, the Flex framework calls the updateDisplayList() function.
Just as with the Arrows component, updateDisplayList's purpose is to position and size the child components to make this component look the way it is supposed to look.
override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void
{
super.updateDisplayList( unscaledWidth, unscaledHeight );
arrows.move(0,0);
linkButton.move(arrows.width,0);
linkButton.setActualSize(unscaledWidth-arrows.width,unscaledHeight);
}
The arrows are moved to the (0,0) position. Then the linkButton is positioned immediately after it. The linkButton is also given a size. Here, unscaledWidth and unscaledHeight will be whatever measure() determined or they will be the explicit sizes given to your component.
And that's all there is. The download source file has it all put together for you along with a sample test program. But take a look at the V2 and V3 components; compare them with the Arrows component. In all cases the Flex framework operates consistently. Because V2 was based on HBox, the measure and updateDisplayList functions were not necessary. When writing a component from scratch you have to do these things yourself.
Now you can write components from scratch - either based on existing components or from scratch. The next article in this series looks at skinning and styling components.
Posted by pent at 11:36 AM | Comments (6)
October 24, 2007
Component Class - Part Three
In the previous article you saw how to create a component in ActionScript and how that mimics a component written in MXML:
| MXML | ActionScript |
|---|---|
| Root tag | class extends |
| Metadata tag | [Metadata above class definition] |
| Child component tags | override createChildren(), using new operator and addChild() function. |
| Properties | Set and Get functions; override commitProperties() |
| Events | Use addEventHandler and specify an event argument to the handler function. |
In this article we'll look at how to make that circle of arrows rotate.
This is a link to the same file download in the previous article; nothing has changed.
Arrow Class
In the first article the cycle arrows is a GIF. Easy to place using the Image component (either in MXML or in ActionScript). That would be enough, except we want to rotate the arrows as the user clicks on the link in the component.
So what's wrong with that? Rotation in Flash is pretty easy, you just set the rotation property to an angle and the object rotates - about its (0,0) point. That's the catch - in Flex a component has (0,0) as its upper-left corner. When you rotate a Flex component by changing its rotation property, it pivots on this corner - it does not rotate about its center.

There are ways around this using a translation matrix, but I think this alternative will prove educational and help you out when you have some awkward things to do in Flex.
Principle
Keep in mind that (0,0) is the upper-left corner of a Flex component and to make life very easy and simple in the Flex framework, the Arrow component is going to keep it this way. The difference is that inside of the Arrow component, the circle of arrows will appear and it will rotate and not the Arrow component itself.
Here's the Arrow component in its entirety, but broken into sections. I think it will be easier to explain this way.
package com.adobe.examples.skins
{
import mx.core.UIComponent;
import flash.display.Graphics;
import flash.display.Shape;
public class Arrows extends UIComponent
{
There really isn't any existing Flex component to extend so the Arrow class extends UIComponent - the base class for every Flex component. UIComponent is what every Flex component inherits from.
createChildren
private var canvas:Shape;
/**
* createChildren (override)
*
* Creates the shape in which the arrows appear. This shape can then
* be rotated.
*/
override protected function createChildren():void
{
canvas = new Shape();
// after drawing the arrows below, I realized they were too big, but my
// calculations for the lines and curves were already figured out. So I
// just scaled the graphic a bit to make it look better.
canvas.scaleX = 0.6;
canvas.scaleY = 0.6;
addChild(canvas);
}
This component has a single child, a
flash.display.Shape , where the arrows will appear. This is the part that actually rotates. The Shape class is a very basic, lightweight Flash class for drawing. It has very little overhead and is ideal for this purpose.
measure
/**
* measure (override)
*
* Return the default width and height
*/
override protected function measure():void
{
measuredWidth = measuredMinWidth = 20;
measuredHeight = measuredMinHeight = 20;
}
So far you've seen createChildren() and commitProperties() - functions which you override to make your component. Here is another -
measure() . This function is critical to making components behave properly with the Flex framework's layout manager. You don't need to have measure() in the CycleSelectButton components because the HBox does this for you - a benefit of using a Container as a basis for your own components.
The measure function is called only when the Flex framework does not know how large the component should be. If you supply an explicit width and height to a component, measure() is never called because the layout manager knows how big it is. Keep this in mind and do not write anything in this function that is critical since it is not always called.
The measure() function's job is to set the
measuredWidth and measuredHeight properties (and optionally, like here, the measuredMinWidth and measuredMinHeight properties). Sometimes measure() can be complex if you have lots of children to the component - you have to measure all of them and then figure out how large the overall component is.
In this case, I create the circle of arrows to occupy a 20x20 area. So that's what I set measuredWidth and measuredHeight to.
updateDisplayList
/**
* updateDisplayList (override)
*
* Position the canvas containing the arrows in the middle of the component. Then
* draw the arrows.
*/
override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void
{
super.updateDisplayList( unscaledWidth, unscaledHeight );
canvas.x = unscaledWidth/2;
canvas.y = unscaledHeight/2;
drawArrows( canvas.graphics );
}
The
updateDisplayList() is another function in the Flex framework called in the life cycle of a component. The updateDisplayList() function is perhaps the most fun - it is were you actually make things happens. In this case two things are done: the canvas Shape with the arrows is positioned and the arrows are drawn.
Remember that the arrows are being drawn within the canvas at (0,0) - so we need to place the canvas Shape where we want its (0,0) to be - and that's in the middle of the component which is (unscaledWidth/2, unscaledHeight/2). If this is confusing, change it to (0,0) and see what happens.
I moved the arrow-drawing into a separate function to make it clearer (this function appears at the end of the class):
/**
* drawArrows
*
* Draws the circle of arrows in the given graphic. The circle is centered
* at (0,0) to make it easy to rotate
*/
private function drawArrows( g:Graphics ) : void
{
g.clear();
g.lineStyle(0, 0x0000CC, 1);
g.moveTo(-10,0);
g.curveTo(-10,-10,0,-10);
g.curveTo(2.5,-11,8,-8);
g.moveTo(8,-8);
g.lineTo(6.5,-13);
g.moveTo(8,-8);
g.lineTo(2.5,-6);
g.moveTo(10,0);
g.curveTo(10,10,0,10);
g.curveTo(-2.5,11,-8,8);
g.moveTo(-8,8);
g.lineTo(-6.5,13);
g.moveTo(-8,8);
g.lineTo(-2.5,6);
}
The
flash.display.Graphics (g) is the Flash entity which places instructions into the Flash Player's display list. Ultimately every component does this. The first thing is almost always clear() so you don't add more graphics - you usually want to replace them. You can read more about the Drawing API in the Flex documentation. You can see that the arrows are a series of
lineTo and curveTo functions about (0,0).
The rotation Property
/**
* rotation - apply rotation to the canvas shape, not to this component
*/
override public function set rotation(value:Number):void
{
canvas.rotation = value;
}
override public function get rotation():Number
{
return canvas.rotation;
}
Here's a trick you may not expect: overriding a very basic property like rotation. If you were to do something like
arrows.rotation = 45 you would and should expect the component to rotate to 45 degrees. But if that happens, the component rotates about its upper-left corner. What we want to do is rotate the Shape instead. By overriding the component's rotate property, we re-direct the value down to the Shape and prevent the component itself from being rotated.
Another benefit of overriding the property is that it will make sense to the developer who uses the component. Telling them that they can rotate the arrows by changing the rotation property is what they expect. Trying to explain they should not use rotation but instead use another set of functions is awkward.
Use in CycleSelectButtonV2
Now open the CycleSelectButtonV2 code and replace the Image component with an instance of the new Arrows component. The code provided in the download already does this; you use the Arrows component like anything else:
- You have to create an instance of it using new Arrows().
- You can add it to the CycleSelectButtonV2 component with addChild().
override protected function createChildren() : void { arrows = new Arrows(); arrows.width = 20; arrows.height= 20; addChild(arrows); linkButton = new LinkButton(); addChild(linkButton); // add a listener for the click on the LinkButton. linkButton.addEventListener(MouseEvent.CLICK, handleClick); super.createChildren(); } - You make it spin by changing its rotation property in the LinkButton click event handler:
arrows.rotation = arrows.rotation + 45;
What's Next
In the next article in this series we'll write this component one more time, but completely from scratch by extending UIComponent.
Posted by pent at 07:22 PM | Comments (3)
October 22, 2007
Now Available in Chinese
Several articles have now been translated into Chinese. You can view them at http://www.zhuoqun.net/index.php/archives/tag/peter-ent on Dreamer's Blog.
It is quite an honor to have someone take time to do this work. Thank you.
Posted by pent at 09:55 AM
October 09, 2007
Flex and Hibernate
For the past month or so I've been working on a new example that shows how to use the Hibernate data assembler in LiveCycle Data Services ES. If you aren't familiar with Hibernate, it is a way to easily persist Java objects - either singularly or in collections and with complex relationships. For example, if you have a data base of employees using several tables, you can make a single Java class that represents the employees and tell Hibernate how to bring it all together. You can load and save these objects using Hibernate and all of the tables will be updated properly.
LiveCycle Data Services ES includes Hibernate. Using the AMF protocol between the Flex client and LC DS you can persist ActionScript objects, too. You can create an Employee ActionScript class and point to a LC DS destination which maps to Hibernate and save and load your ActionScript objects. There's a bit more to it than that, of course, which is why I wanted to make an example.
This example is complex enough that I have broken it into two parts. This is the first part and shows how to use Hibernate with LC DS along with a simple Flex application. The next part focuses a bit more on the Flex side with a more complex application but still using the same example code from this part.
Here are the basic steps:
- You need a database. I've used MySQL 5 for the example. You need to create tables and foreign key relationships. The schema which accompanies this article includes that.
- You need LiveCycle Data Services ES. Once that's installed you follow a few more steps to turn on Hibernate. There is nothing else to download.
- You make some Java beans that represent your objects. There is a Hibernate tool and Eclipse plugin which can do this but I did it all by hand. If this were a larger project I would opt for the tool. Hibernate persists Java objects, not ActionScript objects, which is why you need these Java classes. LC DS will take care of mapping your ActionScript classes to the Java classes.
- You make Hibernate configuration files which maps the Java classes to the database tables. The example I've written keeps these pretty minimal, which is good the first time out. In reading a Hibernate book I can see that very complex things can be done using these files.
- You make corresponding ActionScript classes. When you request data through the remote data service in LC DS you get back ActionScript objects. There are special ActionScript metadata tags which tell the compiler to expect this.
- You make a Flex application.
You also might want to visit this blog to get a more rapid introduction to Hibernate and Flex: Mind the Gap
About the Data
Before going further I should explain the data being used. I work in the Flex support group and so I modeled this example on some of the tools we use to open and track questions from our customers.
The tables include one for Accounts (customer companies), AccountContacts (people who have questions), Consultants (people like me), Cases (the questions asked), and CaseNotes (the progress of the Case). Accounts can also have a Consultant assigned to them and a Consultant can have multiple Accounts assigned. This is a one-to-many relationship. The Java and ActionScript classes reflect this: you'll see Sets in the Java classes and ArrayCollections in the ActionScript classes.
Setup and Installation
To begin this example, install your database and create the tables from my schema. Create a database called "support" and if you are using MySQL 5 you should get no errors when you run the SQL statements. If you are using a different database you may have to change the SQL. This is one good reason to use Hibernate as it masks the database peculiarities from you.
Now install LC DS if you haven't already. Install it using the embedded JRun instance. This will make debugging and development simple.
Active the Hibernate components in LC DS as follows: (steps from documentation here).
Copy <install root>/resources/hibernate/*.jar to your web application's WEB-INF/lib directory (for example, on windows, this might be C:\lcds\jrun4\servers\default\samples\WEB-INF\lib\
Create a new Flex Builder Java project. Have the bin directory point to the WEB-INF/classes directory. Copy the contents of the classes directory to the WEB-INF/classes directory in LC DS. You'll see that there are both .class and .hbm.xml files. It is best if the Hibernate configuration files shadow the Java class files.
Modify your data-management-config.xml file that is in WEB-INF/flex directory. Here's a tip: in Flex Builder, add a new folder to your Java project, but click the Advanced button to make it a link to an existing folder. Browse to the WEB-INF/flex directory. Now you can edit the configuration files right from Flex Builder.
Start LC DS. You should see a lot of output, but no errors. If you do get errors, double-check your work.
Create a new Flex Builder Flex project. Indicate that you want to use LC DS, but compile locally in Flex Builder. You can compile on the server, too if you like. I prefer to leave my source files off the server.
Import the Flex sources into this new project. Notice how the bin directory points to the LC DS flex context root directory. Your compiled files will go right out to the server so all you need to do is run it.
In fact, all you need to do is run the TestingApp application. This is what you should see:
|
|
Click to enlarge |
So how does all this work?
If you open the Flex application you'll see a couple of DataService tags. Note the destination values. Then open the data-management-config.xml file on the LC DS server and find the destination with the same name. Notice how this destination is tied to the Hibernate entity description.
When the Flex application requests all of the Account objects, LC DS uses the Hibernate adapter to get Hibernate to fulfill the query. Hibernate queries the database and assembles a collection of Java Account objects. LC DS then converts the Java classes into an AMF binary stream, including the class name meta data.
The AMF stream arrives at the Flash Player and the Flex code examines the metadata and matches it with ActionScript classes with the same metadata and creates the ActionScript objects.
What you get back in your Flex application is an ArrayCollection of ActionScript Account objects. But there is more than that. Notice how the Account class also defines a collection of AccountContacts. Hibernate has gone and fetches them, too.
I hope this is enough detail to get you going. Leave me some comments if there are parts I could explain better and I'll follow with another article. Once this part is well understood, I'll publish the next part which details a Flex application that makes use of this data.
Hibernate Mapping in Detail
Let's take a closer look at the Hibernate mapping files and how they relate to the application as a whole.
First open the data-management-config.xml file and locate the destination for account.hibernate:
<destination id="account.hibernate">
<adapter ref="java-dao" />
<properties>
<use-transactions>true</use-transactions>
<source>flex.data.assemblers.HibernateAssembler</source>
<scope>application</scope>
2. <metadata>
<identity property="id"/>
<one-to-many property="accountContacts" destination="accountContact.hibernate" read-only="true" lazy="true" />
<many-to-one property="consultant"
destination="consultant.hibernate" lazy="true" />
</metadata>
<server>1.
<hibernate-entity>support.Account</hibernate-entity>
<fill-configuration>
<use-query-cache>false</use-query-cache>
<allow-hql-queries>true</allow-hql-queries>
</fill-configuration>
</server>
</properties>
</destination>
#1: Notice in the <server> section the <hibernate-entity>? The value supplied is the name of the Hibernate entity class to use with this destination. Since it is "support.Account" you'll want to look into the support package for the entity configuration file. Open WEB-INF/classes/support/Account.hbm.xml:
<class name="support.Account" table="accounts"> This names the Java class associated with this Hibernate class entity and the database table it maps to.
<id name="id" column="accountid">
<generator class="native"/>
</id>
If you examine the database table description for "accounts" you'll see that its primary key is the account column. The Hibernate entity element, <id>, shows that the id property of the Java class maps to the accountid column of the "accounts" table.
Look back at the data-management-config.xml destination at #2, the <metadata> for the destination description. See how the <identity> element names the same property.
The data-management-config.xml destination <metadata> also names some associations:
<one-to-many property="accountContacts"
destination="accountContact.hibernate"
read-only="true" lazy="true" />
<many-to-one property="consultant"
destination="consultant.hibernate"
lazy="true" />
Go back to the Account.hbm.xml file and you'll see corresponding relationship mappings:
<set name="accountContacts" inverse="true" >
<key column="accountid" />
<one-to-many class="support.AccountContact" />
</set><many-to-one name="consultant"
column="consultantid"
class="support.Consultant"
not-null="false" />
Since an Account can have zero or more AccountContacts, the first association declares a one-to-many relationship (one Account to many AccountContacts). In Hibernate, this is represented as a Set and corresponds to the java.util.Set class in the Account java class. The Set's name (accountContacts) is the name of the property in the Java class; the set names the column to key off of and the one-to-many element identifies which Hibernate entity class to use for those elements.
Back in the data-management-config.xml file, the one-to-many association is repeated to let the Data Services Hibernate Assembler know the relationships should be formed.
The relationship between a Consultant and an Account is the reverse: many Accounts to one Consultant. So a many-to-one association is used. When Hibernate sees the many-to-one element it knows that the Java class property, "consultant" will be of the type, support.Consultant and be a single element, not a collection.
Where's the ActionScript?
When dealing with the server-side there is no ActionScript – that's in the Flex client. Hibernate uses Java classes. For example, support.Account.
The Data Services Hibernate Assembler takes the Java class instances returned by Hibernate (eg, support.Account) and creates a byte stream in AMF format. Part of the byte stream (or serialization) of the class instances contains the name of the Java class.
Back in the Flex client, the receipt of the byte stream causes a look-up of an ActionScript class with metadata that maps the Java class name to an ActionScript class. The Flex client code then instantiates an ActionScript class (eg, support.Account) and fills its properties with the corresponding values from the byte stream.
Posted by pent at 11:21 AM | Comments (12)
September 27, 2007
Sharing Data Between Applications
This is a topic that comes up from time to time and is applicable to both Flash and Flex as the solution lies within the Flash Player.
Let's say you have a customer's profile you'd like to store on their local machine. Perhaps your web site has multiple HTML pages, some with Flash or Flex applications and you would like those applications to use the same customer profile information.
Providing this is not a lot of information, the SharedObject is the best way to go. SharedObject is a class for, well, sharing data. A small data file is stored on the local computer and requires the end-user's consent (which is granted by default). The end-user also has control over how much space to allocate for ALL SharedObjects - not just for your applications. Bear these restrictions in mind when writing your applications - you may need to query the user for the information if it cannot be stored and retrieved.
Download Sample Flex Application
Using SharedObject is pretty easy. Here's how to store a String and a Number:
var so:SharedObject = SharedObject.getLocal( "MyAppData" );
so.data.customerName = customerData.name;
so.data.serialNumber = customerData.serialNumber;
so.flush();
And that's it. A local SharedObject is created with the name "MyAppData". The SharedObject has a public member, data. Noticed that I didn't set data directly, but set properties on data itself. That is very important - you cannot change the value of data, you must add properties to it - otherwise your information will not be saved.
Reading the information is just as easy:
var so:SharedObject = SharedObject.getLocal( "MyAppData" );
if( so.data.customerName ) customerData.name = so.data.customerName;
if( so.data.serialNumber ) customerData.serialNumber = so.data.serialNumber;
Notice that I tested each property to see if it exists before using it.
A common question is if it is possible to save ActionScript class instances. Consider this example: you have a Person class which has members like name and age. The class also has a member address which is typed to be the ActionScript class Address. What you'd like to do is this:
var currentPerson:Person;
...
so.data.person = currentPerson;
This generally works, but what is saved to the SharedObject is NOT an instance of the Person class. Rather, so.data.person is a plain ActionScript Object - all information with respect to the class has been removed.
When you want to read this information, you need to assign each part. For example:
currentPerson.name = so.data.person.name;
currentPerson.age = so.data.person.age;
currentPerson.address.street = so.data.person.address.street;
...
It is also not guaranteed that your class will be successfully (or completely) turned into nested ActionScript Objects.
A better way to serialize your class is by implementing a serialization technique. One way is to use flash.utils.IExternalizable; you could also use XML. You don't really need to implement this interface as SharedObject doesn't know anything about IExternalizable. It is just good practice to do so.
Implementing IExternalizable requires your classes to have two functions: writeExternal and readExternal. Basically you convert your class to a series of bytes which can be stored in the SharedObject and read back later. For example:
class Person implements IExternalizable
{
public function writeExternal( output:IDataOutput ) : void
{
output.writeUTF(name);
output.writeInt(age);
address.writeExternal(output);
}
public function readExternal( input:IDataInput ) : void
{
name = input.readUTF();
age = input.readInt();
address.readExternal(input);
}
}
The Address class would do the same. The IDataOutput and IDataInput interfaces are implemented by several classes. You can use ByteArray for use with SharedObject. Here's how to save your Person class instance:
var bytes:ByteArray = n




