August 23, 2007

My first small Cairngorm Flex application (with explanation)

Follow-up to WiMIC Browser – my first big Flex application from Transversality - Robert O'Toole

I have just constructed my first Cairngorm application: an Adobe Flex application that uses the Cairngorm application framework, implementing the MVC pattern. The app doesn't do much, initially displaying "hello everyone", along with a button that translates that message, and a second button that changes the background colour of the component. Exciting stuff! Not. But the Cairngorm framework is. Download the source code for my demo application.

Explanation


Here is a screenshot of the Navigator window for the project:

Navigator

The Cairngorm source code is included in the "com" folder (although it could be compiled and included as an external library). The "uk.ac.cairngormtemplate" folder contains my application. This has six subfolders, each containing classes responsible for different parts of the MVC architecture: view, control, command, business (actually meaning data and comms services), model, vo (value object). As with all Flex applications, there is a single container mxml file, called Main.mxml (an mxml file is equivalent to a html file, with code, styles and visual components). I'll start my explanation of this app and Cairngorm with this top-level container.

The Main.mxml file contains four key items:

  1. a Services component - this contains all of the services used for connecting to external data sources etc;
  2. the AppController - this maps events onto commands, so that when a ui dispatches an event (a request for something to happen), the correct code does the required job;
  3. the AppModelLocator - this stores and indexes all of the data models used in the application, all of the data is stored in one place!
  4. a ViewStack listing all of the alternative user interface views that the app can display.


Here's the code for the ViewStack:

<mx:ViewStack width="100%" paddingBottom="10" paddingTop="10" resizeToContent="true" selectedIndex="{model.currentView}">
   <view:InitialView />
   <view:AlternativeView />
</mx:ViewStack>   

There are two views in this application, an initial view and an alternative. Each view is defined in its own mxml file in the "uk.ac.cairngormtemplate.view" folder. Notice how the selectedIndex property of the ViewStack is bound to the .currentView property contained in the modelLocator (initially set at 0, which means that the first view in the stack is displayed). This means that the currently selected view may be changed by changing the model.currentView property (more on that below).

So now let's drill down into the InitialView component. We can then see the details of what is presented to the user, and what happens when the user responds to that interface.

InitialView is itself an mxml component based upon the standard VBox component. It contains some script and some UI components. Firstly, the script contains a bindable reference to the AppModelLocator singleton. This means that we can bind UI components to data in the AppModelLocator. There is in fact a text component that is bound to a value object (a class that wraps a set of value properties):

<mx:Text text="{model.messageVO.message}" />

Initially this displays the message "Hello everyone".

Below this text component there is a button "translate". Clicking this button calls an actionscript method in the script on the page. The method is called translate(). It could at that point do some validation, or request further input. However, in this case all that we want it to do is fire of a request for the text "Hello everyone" to be translated.

InitialView
The least impressive Flex app ever

This is where Cairngorm starts:

private function translate():void
{
   var cgEvent : DataChangeEvent = new DataChangeEvent("Dumelang");
   CairngormEventDispatcher.getInstance().dispatchEvent( cgEvent );               
}

The method creates an instance of the DataChangeEvent, passing it the new message "Dumelang". The DataChangeEvent is defined in the "uk.ac.cairngormtemplate.control" folder. It is a cairngorm event extended to carry our message. We can create events that can carry whatever data we need to be passed to a command. (For example, a user types their username and password into a login box, this is then wrapped in a LoginEvent, and the event dispatched. A LoginCommand receieves the event and attempts a login using a LoginDelegate and login service. If succesful, the command changes the current view to one appropriate to a signed in user).

The next step is to dispatch that event and its message to the Cairngorm controller. This should then get passed on to the required "command" object (the command object contains the code for executing the requested command). But how does the controller know which command object to use? Events are mapped on to commands in the control.AppController class:

public class AppController extends FrontController
{

   public static const DATACHANGE_EVENT : String = "DATACHANGE_EVENT";

   public function AppController()
   {
       addCommand( AppController.DATACHANGE_EVENT, DataChangeCommand );
   }
}

Our request (to translate "Hello everyone") is then passed to a DataChangeCommand object. This is where we do the work that results in the translation. In this simple example, the .messageVO.message of the modelLocator is simply changed to read "Dumelang". However, we could instead refer to an English-Steswana dictionary to retrieve the translation. This might even require the use of an external data service. The DataChangeCommand would then delegate the work of sending this external request to a Delegate class in the "business" folder. The delegate, on retrieving the required translation, calls back to the DataChangeCommand to complete the requried command, or alternatively calls a seperate command.

So, with the text control on the current view bound to the .messageVO.message property in the modelLocator, and that property now altered (by DataChangeCommand) to "Dumelang" that is precisely what the end user sees on their screen.

But what if we also need to change the current view, for example to the AlternativeView control in the ViewStack? Easy. The command simply alters the .currentView property of the modelLocator. As the selectedIndex property of the ViewStack is bound to .currentView, it immediately changes.

In this example, at the end of DataChangeCommand, a second command is requested using a class that I have called ViewChangeEvent.

var cgEvent2 : ViewChangeEvent = new ViewChangeEvent();
CairngormEventDispatcher.getInstance().dispatchEvent( cgEvent2 );

This class calls ViewChangeCommand, which simply alternates between the InitialView and the DefaultView.

AlternativeView
Look - it speaks Setswana! and now the view has changed to one with a white background! Hoorah!

Conclusion


This may be a simple example, but I can already see how using the Cairngorm framework will simplify the task of building very complex applications, resulting in better, more rational and sustainable code.

- No comments Not publicly viewable


Add a comment

You are not allowed to comment on this entry as it has restricted commenting permissions.