Quick cheat notes for Flex's MXML and State.

MXML is basically a quick way to describe the View component to Flex. It can define pages, components, containers etc. So it mixes in quite a bit in the same haphazard way the JSP, PHP, ASPs, Visual Studio components etc allow. It looks like it can get messy quickly Additionally ActionScript can be embedded in MXML documents under CDATA which is a recipe for spaghetti code and difficult to debug behavior. MXML can define visual components such as containers (mx:VBox and mx:HBox) as well as UI interface controls (mx:Button and mx:ComboBox). There are also non-visual components such as Data binding and Utils code. They are probably best not done in MXML (see spaghetti code pattern). The model/controller patterns should use ActionScript even though MXML is compiled down to ActionScript and is an XML representation of ActionScript classes and packages. Flex provides a client/desktop paradigm in a web environment. So it is bad to think of Flex/Flash in web page terms. It is a client-based application. As a result the interactions between components, state and data is done through events rather than http requests and tacked on publish/subscribe mechanisms.

There are two types of events, User Events and System Events. The user events are in response to a user performing an action with a component, such as clicking a button. The user events can be attached to a MXML declaration directly and inlines (same as javascript), or a handler can be registered in the MXML declaration and the event handling code be done in ActionScript either in an mx:Script tag and under a CDATA or through ActionScript in an included file mx:Script and source="name_of_actionscript_file.as"

Flex includes the ability to manage State directly to over-ride views. The state functionality is defined in the UIComponent object. States can be defined in MXML or ActionScript but since it is a view technology, it is best performed and defined in MXML. States are defined with mx:States and the children mx:State where the State tag can add/remove components, set properties of components/objects, set styles of components, set event handlers and perform custom overrides where new events can be defined. Adding and removing components with state changes is like doing a display:none on a div in html. The component remains in memory but is not visible.The properties of component can be modified when state is changed via the mx:SetProperty tag. Style is modified with mx:SetStyle, and handlers added with mx:SetEventHandler.

The framework that swallowed the Gang of Four book.

PureMVC is an MVC framework where you dont get to work with the Model-View-Controller part of it at all. The MVC part of the framework are Singletons that are accessed by Proxies, Mediators and Commands. There is a fourth Singleton, a Facade, which enables the Proxies, Mediators and Commands to communicate with each other in a meaningful way.

The Facade exposes methods to add, remove and get; proxies by name, mediators by name and commands by name. It also has a method to send a notification (another pattern). The framework intends that the developers do not interact with the MVC structure directly, instead using names and the central Facade to interact with the MVC structure via the secondary patterns of proxy, mediator and command.

The mediator interacts with the View's data via notifications. A mediator can be interested in multiple notifications. The proxy follows the same mechanism, it interacts with the Model via notifications. The controller contains mappings between commands and notifications. A command may retrieve and interact with a proxy, notify a mediator, or execute another command object. As per the GoF command pattern there is a SimpleCommand and MacroCommand where the latter's execute method can implement the execute interface on an aggregate of SimpleCommand's execute method.

Notifications are done through the Observer pattern. The observer carries a reference to the object that wants to be notified and the method that the notification will be broadcast too. It is up to the View to manage the mapping of notification names to observers when a notification is sent.

So what are the pros and cons of using this? The pros is that it is well defined as per the GoF book which has become the franca de lingua for software developers. The downside of the Gang Of Four book usage is that it causes abstraction proliferation where in many instances a simple procedural or concrete object that cracks a developers ribs is simpler, easier, less fragile and less confusing. Another downside is that pureMVC code is not portable unless you use pureMVC again. From experience, I have already seen that a classically OOP designed system bears no relevance in a pureMVC system, essentially removing any portability for that code to other systems. This system also suggests that it is over-designed as the actual MVC structure is abstracted away from the developer into proxies, mediators and command objects. Then again, this level of design and abstraction may prove more maintainable in the long run. We shall certainly find out.

Note It reminds me more of a CORBA system than an MVC one. I worked on a large CORBA system several years ago. It was solving the issue of multiple desktops running the same application. Apache and HTTP made that whole set up redundant. I recall a website was placed over the top of the CORBA system since so much work had gone into the underlying structure. Not sure that pureMVC's level of abstraction is solving a known problem domain, as I have worked with smaller MVC frameworks that did not run into blending of responsibility issues.
avocadia:
the GoF book which has become the franca de lingua for software developers

Maybe so, but I for now I will be using this framework as a an argument: "Look, see where your central planning has taken us? GoF == Road to Serfdom!!!!!" :- )
A quick discussion of the Observer and Notification pattern in the pureMVC framework.

Model

The model is interacted with through Proxies which can send notifications, but do not receive them. A command will operate on a proxy object directly through a method call, such as, demoProxy.changeThis(Obj), and the proxy, realizing that its state has changed, can then send out a notification for other mediators and commands to react to its new state.

View

The View is interacted with by mediators which can have multiple notifications (think events) they are listening to. Mediators can send and receive notifications, as well as allow other parts of the system to ask what notifications they are interested in.

Controller

Commands are mapped to notifications by the central Facade. The controller responds to notifications and, based on notification name, and the mapping, will fire the command and execute it. A command interacts with a proxy (model) directly through a method call. A command can also interact with a mediator (view) directly or through a notification. The direct manipulation of a mediator can make the controller and view tightly coupled, but is possible within the system.

Rounded Corners and Drop Shadow with Flex

This is a vbox component with a canvas and label inside it. Setting the component's properties is similar to VB or other Visual Studio happy languages. There is none of the mess that CSS and HTML would require to achieve this same effect.

This is the code that creates the screenshot above.

Quite simple. Flex becomes more difficult once MXML and Actionscript are mixed which simple examples such as this don't require.

Copying Objects in Actionscript 3

Objects can be cloned in Actionscript 3 using the ByteArray object.

private function cloneObject(obj:Object):Object {
var byteArr:ByteArray = new ByteArray();
byteArr.writeObject(obj);
byteArr.position = 0;
var clonedObj:Object = byteArr.readObject();
return clonedObj;
}

An issue is that if you want to stuff them in an ArrayCollection as a strongly typed object, you cant cast as part of the process to the object. They end up in the ArrayCollection as null. It is better to make a copy() method in the object that needs to be cloned and created a new instance of that object and then filling up its member variables anew.

public function copy():Article {
var article:Article = new Article();
article.title = this.title;
article.body = this.body;
return article;
}

One of those things where you try something and it doesn't work.

Typesafe Enums in Flex

Flex doesn't have the linguistic support for enums that Java has. They are often just used as a constants file with a unique namespace in Flex.

The other difficulty is that larger Flex projects can cause colliding worlds between Flex developers, Javascript developers, Java/C#/C developers and other front-end technologies as well. As a consequence there can be many differing ideas as to how to do things as what is considered the norm for each language and platform gets written into one codebase.

The type safe enum pattern can be adhered to in Flex but with the difficulty of Actionscript having no private constructors. For instance:

package {
public final class CreditCardEnum {
public static const AMERICAN_EXPRESS:CreditCardEnum = new CreditCardEnum("American Express");
public static const MASTERCARD:CreditCardEnum = new CreditCardEnum("Mastercard");

private var type:String;

public function CreditCardEnum(type:String):void {
this.type = type;
}
}
}

Where this would be instantiated with:

var creditCardEnum:CreditCardEnum = CreditCardEnum.AMERICAN_EXPRESS;

Rather than hiding the private constructor off as a class outside the package name, it is often easier in the ECMAscript based languages to put in a comment saying please don't use the constructor, instead use it as an enum. Alternatively type safe enums can be created by the enum class itself, though again this requires the discipline of passing in the object's public static const's as the argument.

package {
public final class DebitCardEnum {
public static const BEAR_SEARNS:String = DebitCardEnum.create("Bear Stearns");
public static const WAMU:String = DebitCardEnum.create("WaMu");

private var type:String;

private static function create(debitCardType:String):DebitCardEnum {
var enum:DebitCardEnum = new DebitCardEnum();
enum.type = debitCardType;
return enum;
}
}
}

Where this would be instantiated with:

var debitCardEnum:DebitCardEnum = DebitCardEnum.WAMU;

Both examples are typical of the trade offs you make in Flex and ECMA script languages with object oriented patterns.

Flex: Array from ArrayCollection

I tend to think of the Flex arrays and collections with a Java mindset, which is bad, as they don't follow the same patterns. Consequently I have a bad habit of either coercing an ArrayCollection to an Array implicitly, or explicitly and being mystified when they aren't a clean cast. They are different of course: Array and ArrayCollection documentation from the AS3 docs. The Array is used compositionally in the ArrayCollection and is a wrapper around the Array that implements the List and Collection functionality. The Array can be pulled from the collection via:

import mx.collections.ArrayCollection;
var arrCol:ArrayCollection = new ArrayCollection();
var arr:Array = arrCol.source;
Flex's equivalent of printf is StringUtil.substitute();

StringUtil.substitute("Embed {0} and {1} here", "zero", "one");

Which resolves to the string, "Embed zero and one here." Particularly useful for pulling strings from a resource bundle and then populating them with variables.
Got this error while writing in Flex; "Error #1025 An invalid register was accessed" which suggests that the actionscript in a swf is invalid. Turns out it is due to the namespace not being set back to the default:

default xml namespace = new Namespace("");

I added this at the end of the XML processing.

Ironically it is destroying our unit tests where we are starting to see the error with recurring frequency. Bizarre. Personally I don't think the flex compiler or IDE are that great. They are slow, sloppy, frustrating and often hopeless inaccurate.

Update One of the team found that another work around for this is to have the method which uses namespaces at the very bottom of the class. It appears that using the namespace affects the namespace of the AS3 file that is using E4X.

Update II It gets worse. I was debugging a method under where I had put default xml namespace = new Namespace(""); and the debugger instead of hitting the method below it, hopped up into another method above where that namespace line was. So the namespace obviously steals scope. Quite nasty. The solution is to put methods below that, above it.
I was trying to install the subclipse plugin for Flash Builder on OSX so I could build Flexcover against Flex 4's SDK. Anyway I updated eclipse first to try and get the Mylyn stuff in and *choke*:

Cannot launch the Update UI. This installation has not been configured properly for Software Updates.

I found these links, this is the bug against eclipse and this is a solution from stackoverflow. Unfortunately going to Preferences -> General -> Capabilities -> Classic Update and checking that box did not fix it for me. Still stuck.
Next 10 articles

Most Popular on South Sea Republic

The articles that have been viewed the most:

Most Popular Restaurants in Phoenix

Phoenix Eats Out is the restaurant review site for Phoenix, Scottsdale and Old Town Scottsdale which lists the modernist and contemporary restaurants, taverns and bars in the greater Phoenix area. This is the list of the most popular restaurants pages from phoenixeatsout.com that have been viewed the most; My personal favourite restaurants in Phoenix are AZ88, Postinos, Bomberos with Grazie, Humble Pie, Orange Table, The Vig, Fez and others coming close behind. View the complete list with the photo-journalistic style images on phoenixeatsout.com

Most Popular Hikes in Arizona

Arizona is an outdoor state and has lots of hiking in the city and around the state. Phoenix is unusual for most cities in having several large mountains in the center of the city with great hiking. Anyone who comes to Phoenix has to do the Echo Canyon trail on Camelback and the Summit Hike on Squaw Peak or Piesta Peak. The views of the city, suburbs and surrounding mountains are wonderful from Camelback and Piesta Peak. For more experienced hikers there is the McDowell Mountains in North Scottsdale that has several difficult and strenuous hikes in Tom's Thumb and Bell Pass. Alternatively, you can hike the highest mountain in Arizona. At 12,600 feet Humphrey's Peak is a long and difficult hike.

Alternate Australian Constitutions

Between 2004 and 2009 this site, southsearepublic.org, was a constitutional blog based on scoop which focused on Australian and global constitutional issues. One of the strongest aspects of it was the development of constitutions by those involved in the blog. These constitutions are the outcome: The constitutions were built using principles from Montesquieu's separation of powers, the enlightnment's universal political rights and the ancient Athenian technology of sortition and choice by lot.

Archives For South Sea Republic

South Sea Republic started in 2004 as an Australian constitutional blog in 2004 based on scoop software. It was an immigrative outgrowth of Kuro5hin. The archives for each year since then; The articles are ordered by views.

Who Is Cam Riley

Cam Riley I am an Australian living in the United States as a permanent resident. I am a software developer by trade and mostly work in Java and jump between middleware and front end. I originally worked in the New York area of the United States in telecommunications before moving to Washington DC and working in a mix of telecommunications, energy and ITS. I started my own software company before heading out to Arizona and working with Shutterfly. Since then I have joined a startup in the Phoenix area and am thoroughly enjoying myself.

I do a lot of photography which I post on this website, but also on flickr. I have a photo-journalistic website which lists the modernist and contemporary restaurants in phoenix. I have a site on the Australian Flying Corps [AFC] which has been around since the 1990s and which I unfortunately lost the .org URL to during a life event; however, it is under the www.australianflyingcorps.com URL now. The AFC website has gone through several iterations since the 90s and the two most recent are Australian Flying Corps Archives(2004-2002) and Australian Flying Corps Archives(2002-1999) which are good places to start.

Websites Worth Reading

Websites of friends, colleagues and of interest;