MXML is object oriented. Many do not realize that MXML generates an ActionScript 3 Class at compile-time and thus can be used seamlessly via the “new” constructor. If you want fine grained control of your UI, using MXML class instances can bring another level of fidelity to your applications.
WARNING!!! There is one mistake you can make here that will leave you frustrated. Be careful with naming your MXML components as they generate a similar named “.as” file at compile-time. These generated files are hidden unless you use the “-keep” compiler flag. The error is to use similar names for MXML and AS3 classes. This can lead to a mysterious compiler error and will leave you stuck in the mud!!! You have been warned.🙂
Here is a small application that creates 3 MXML class instances using ActionScript and uses the DisplayList API (addChild/removeChild) to swap the UI elements in an out of a panel. The effect is similar to a ViewStack but allows fine grained control over everything including caching the instances at runtime.
Download these two files, compile MXMLViaNew.mxml:
The key here are these lines:
one = new ViewTemplate();
//create an instance of ViewTemplate.MXML via ‘new’
one.labelName = “Matt has eaten two Dodgy Prawns!”;
//edit the labelName property!
panel.addChild( one );
//add the instance into the panel
See with containers you are really working with the DisplayList in Flash Player 9, Flex simply rides atop all this lower level logic. Once you realize that MXML generates a class and can be used with the “new” contructor, Flex gets 100X more interesting. When I learned this it was a huge breakthrough for me and allowed me to go much deeper into the components and the framework.
I also really like this line of code. It has an elegance that is hard to describe:
if( one ) if( one.parent ) one.parent.removeChild( one );
The line reads like this:
if instance “one” exists and one is attached to the displaylist (has one.parent), remove it through itself ( one.parent.removeChild(one) ).
Pure Ninja AS3 there! HEEEEEE-YAAAAAAAHHHHHH!!!
Matt Voerman and I were in Singapore last year for MAX APAC. At dinner in Singapore we has some “Dodgy Prawns” and when Matt asked me for a sample today of MXML via the ‘new’ constructor, well I integrated the joke. Sorry for the Prawn humor.