Thursday, January 22, 2009

How to Make External Components Available to Your Flex Code

MXML tags correspond to ActionScript classes or properties of classes. Flex parses MXML tags and compiles a SWF file that contains the corresponding ActionScript objects. For example, Flex provides the ActionScript HBox class that defines the Flex HBox control. In MXML, you create a HBox control by using the following MXML statement:
<mx:HBox id="mainWindow"  width="100%" height="30" 
borderSkin="{components.TopBorder}" backgroundColor="#A5A7Ad"
backgroundAlpha="0.75" cornerRadius="15" paddingLeft="0"
paddingTop="0" paddingRight="0" paddingBottom="0"
verticalGap="0" verticalAlign="middle">

When you declare a control using an MXML tag, you create an instance object of that class. This MXML statement creates a HBox object, and initializes the borderSkin property of the HBox object to the components.TopBorder Class. To avoid compilation error, you need to make externally defined classes and packages available to your code by using import statement. For components.TopBorder, you need to import it like this:
<mx:script>
<![CDATA[import components.TopBorder;]]>
</mx:Script>
It is possible for you to omit this import statement if you have other components from the same package being referenced in the same MXML file. Say, in the same MXML file that references components.TopBorder, we also have the following MXML tag which references VStack from the same package (i.e., components):

<components:VStack id="worklistComp"  width="100%" height="100%" 
headerStyleName="StackLabel" backgroundColor="#e8eaed" boderThickness="0">

To avoid compilation error, you need to add an namespace declaration as this:

<mx:windowedapplication xmlns:components="components.*" 
width="452" height="364" layout="vertical" ...>

Because the reference of components.VStack has made components package available to your code by MXML compiler, you don't need to import it again.

In summary, you always need to make externally defined classes and packages available to your Flex code by:
  • If you reference it in MXML tag, you use xmlns attribute to declare a prefix and its path (i.e., xmlns:components="components.*") and use that prefix in the tag name (i.e., <components:VStack>).

  • If you reference it in MXML attribute or node value, you use ActionScript import statement to make it available.

No comments: