Learning Flex – Lesson 7, Creating Components with MXML

Components let you modularize your application. This allows you to build and maintain components separately and hopefully re-use them in later endeavors. To allow this, they should be self contained and loosely coupled.

All Flex components are ActionScript classes. The base class for visual components is UIComponent. Below this, there are general groupings of classes based on their behavior.

To build a component, create an MXML file with the name of your component. As it’s a class, it should follow convention and start with an upper case letter.

A component looks like an ordinary MXML file but instead of the root tag being mx:Application, you use the component type you wish to extend or group functionality under.

To use the new component in a different file, you must add an XML namespace to be able to access it (similar to the way you’d use an import statement to access a pure ActionScript class). Normally you would group similar components together in subdirectories so you’d end up with something like charts/lineCharts/MySuperChart.mxml The namespace is declared alongside the mx namespace definition and for our example, would be xmlns:c="charts.lineCharts.*" the component can then be instantiated in the body just like a regular mx component – <c:MySuperChart/>

A custom component does not have to be a visual component. It could be a purely data related or computational class. In this case, we would use UIComponent as our root tag as this is the base class, it’s the lightest weight component we can use.

Pop up windows

The TitleWindow class can show a close button so it’s often used for pop ups. The close event is used to process this action. The PopUpManager class has a static method removePopUp() which can be called for the close event. The remove method requires a reference to the window to close which would normally be this to indicate that you are telling the TitleWindow to close itself.

We can create  a TitleWindow custom component to define our pop up and then use PopUpManager.createPopUp() to display it. The createPopUp method takes three parameters:

  • parent – a reference to the window to pop over
  • class – a reference to the class of object you want to create
  • modal – a boolean that indicates if the window is modal (consumes all input) or not (defaults to false)

In the file where we’re using our custom TitleWindow class, it could look like:

var popup:IFlexDisplayObject=PopUpManager.createPopUp(this,MyCustomTitleWindow,true)

If you need to pass data to your custom pop up, you would declare the popup variable to be the type of your custom class and then use a class cast to convert the output of the create function into your custom class.