Derek Santos

Flex IMXMLObject Interface

By Derek Santos – Consultant

This hidden gem in Flex can really help keep your MXML code clean and separated from your view logic. A great way to use it is to encapsulate your view logic into a ViewHelper. IMXMLObject has only one function.

1
function initialized(document:Object, id:String):void;

Here is Adobe’s documentation for this function:

“Called after the implementing object has been created and all component properties specified on the MXML tag have been initialized.”

What this means is that once the parent is created and has intialized its properties, it will pass a reference of the parent to your IMXMLObject implementation. So, as an example, let’s create a simple ViewHelper. First, create a class and implement IMXMLObject.

ViewHelper.as

1
2
3
4
5
6
7
8
9
class ViewHelper implements IMXMLObject {
   
    public var view:MyView;

    public function initialized(document:Object, id:String):void {
        this.view = document as MyView;
    }
   
}

Notice that I am keeping a reference of the view by assigning the value of document to an instance variable called view. Once you do this, you can work with your view and apply any logic you may need.

Once you’ve created your ViewHelper, you simply need to declare it in your MXML file. In this case, that would be MyView.

MyView.mxml

1
2
3
4
5
6
7
8
9
10
11
<s:Group
   xmlns:fx="http://ns.adobe.com/mxml/2009"
   xmlns:s="library://ns.adobe.com/flex/spark"
   xmlns:local="*"
   >

    <fx:Declarations>
        <local:ViewHelper id="helper" />
    </fx:Declarations>
   
</s:Group>

Notice that you do not need to pass a reference to “this” anywhere. This keeps your MXML very clean and makes the ViewHelper a little more portable. Comments are welcome!

Share

Tags: , , ,

Leave a Reply