One of the most powerful aspects of Flex is that it creates a simple mapping between tags and ActionScript classes. It’s a simple concept, but time and time again, I find that people who don’t know Flex have trouble understanding how this works, or why it would be useful.
For those of you who are new to Flex, here are the rules, along with some simple examples to get started with this concept.
Example 1 — the first three rules
Rule 1 — Each tag corresponds to a new instance of class Tagname
.
Rule 2 — Every attribute turns into a property on the object.
Rule 3 — Every tag with an id turns into a variable of that name.
Let’s say you have a class that looks like this:
public class Contact
{
public var home : Location;
public var work : Location;
public var firstname : String;
public var lastname : String;
public var isFriend : Boolean = false;
}
You can create an instance of it through an MXML file that looks like this:
<Contact id="myContact" firstname="Susan" lastname="Smith" isfriend="true" />
Roughly speaking, the MXML above is equivalent to the following ActionScript:
var myContact : Contact = new Contact();
myContact.firstname = "Susan";
myContact.lastname="Smith";
myContact.isFriend=true;
Simple, eh? Notice that the MXML compiler knows how to deal with all the built-in types. Strings stay as strings, but Booleans turn into true Boolean values, not the string “true”.
But what if you have types that are more complex? That is what rule 4 is for.
More »