Christophe Coenraets posted an entry on his blog demonstrating four different techniques to write a simple temperature converter application.
The purpose of the entry was specifically to demonstrate four different ways to accomplish the same thing–showing how flexible Flex really is. The goal for this application was to separate the ActionScript out of the MXML files.
I’d like to follow up on this entry and demonstrate a fifth approach. This is something one of the Flex engineers proposed earlier and in my opinion is the cleanest method. Instead of using an <mx:Script> tag and including functions that get dropped into the current class, we can create a Controller class and link it through tags. This keeps tags in MXML, ActionScript in external files, promotes OOP programming, and simplifies reuse.
Here is the MXML file using this approach:
<?xml version="1.0" ?>
<mx:Application xmlns:mx="http://www.macromedia.com/2003/mxml"
initialize="appController.initialize();">
<TempConverterController view="{this}" id="appController" />
<mx:Label text="Temperature in Farenheit:" />
<mx:TextInput id="farenheit" width="120" />
<mx:Button id="myButton" label="Convert" />
<mx:Label text="Temperature in Celsius:" />
<mx:Label id="celsius" width="120" fontSize="18" />
</mx:Application>
Notice the TempConverterController class which. We bind the MXML generated class to the controller as the view and open initialization tell the controller to initialize itself. Here’s the ActionScript for
TempConverterController:
class TempConverterController {
[Inspectable]
public var view;
function initialize() {
view.myButton.addEventListener(”click”, this);
}
function click(event) {
view.celsius.text=(view.farenheit.text-32)/1.8;
}
}
This is a clean little class that stands by itself. This is a very simple example, but is easily expanded to implement a real MVC paradigm within Flex applications and keep MXML totally separate from ActionScript.
(I want to thank the Flex team for granting me permission to post this information).
What about using something similar to XML Events as defined in the W3C’s XForms spec (http://www.w3.org/TR/xml-events/), where event binding can be done with a seperate XML document containing Event binding tags? That way your UI markup has absolutely no event specific information in it. You already have something similar with the tag for binding data to the UI.