Being new to Flex, I'm having epiphanies and revelations on a daily basis. I love it, but I hope the frequency of these events will diminish.
Here's my latest epiphany. I probably should have just known this already. I blame it on my percieved notion that there just aren't any good books available yet for Flex 3, so stubbornly I wait and beat my head.
My Epiphany on What Happens when MXML is converted into ActionScript
I want to explain something I didn't initially understand about how MXML is converted into ActionScript. MXML tags represent ActionScript objects. So if I want to declare a
LineChart object and set the values of it's
height properties, I would do this in MXML:
<mx:LineChart id="myChart" width="200" height="200" />
That would make a very boring line chart. When this MXML is converted into ActionScript it would look something like this:
import mx.charts.LineChart; private var myChart : LineChart = new LineChart(); myChart.width = 200; myChart.height = 200;
But what if the
LineChart object had a property that required another object, not just a simple text string or number? This is a silly question in the context of ActionScript, but how do you pass in an object like this when you're using MXML?
- Use data binding techniques
- Use data binding but w/simple anonymous objects you define inline
- Pass the object in by adding it as a child tag to the object in question
The last option is what didn't click for me right away. For example, to configure the background color of a chart, you set the
fill property of the
LineChart object. But the
fill property needs to be an object that implements the
IFill interface (a
LinearGradient). To do this in purely MXML, you therefore have to do this:
<mx:LineChart id="myChart" width="200" height="200"> <mx:fill> <mx:SolidColor color="0x000000" /> <!-- black --> </mx:fill> </mx:LineChart>
What's happened here is subtle (well for newbies like me, atleast). Each tag always starts w/it's namespace (the "mx:"). What follows the "mx:" always seemed to be the name of a class. So
<mx:LineChart> is a
LineChart object. But look at the first child of the
<mx:LineChart> tag, it's name is
fill and there is no class named
fill in the Flex API. The fact that it starts w/a lowercase letter is a big clue.
So here's my big epiphany: In MXML, a child tag is just a property of its parent.
Which means that the following are equivalent ways of setting properties of objects in MXML.
The normal way that didn't blow my mind:
<mx:LineChart width="200" />
Or this way, which sort-of-did-until-now:
<mx:LineChart> <mx:width>200</mx:width> </mx:LineChart>