Search code examples
apache-flexflashactionscriptmxml

How do I access the root element of an MXML document if I can't set an id?


If I wanted to do something like this:

<mx:Canvas  xmlns:mx="http://www.adobe.com/2006/mxml" 
            horizontalScrollPolicy="off" 
            verticalScrollPolicy="off"  
            xmlns:view="com.foo.bar.view.*" 
>
    <mx:Script>
      <![CDATA[
        myWidth = 100;
        myHeight = 200;
        myCanvas.width = myWidth;
        myCanvas.height = myHeight;
      ]]>
    </mx:Script>
</mx:Canvas>

How would I get a handle on myCanvas (where I'd want myCanvas to be the root )?


Solution

  • To access the component specified by the root node from within an mxml file, you can use this keyword. Any code inside an mxml runs in the context of this object - you can as well omit the keyword if you don't have any local variable by the same name.

    this.width = myWidth;
    this.height = myHeight;
    

    For your second question:

    Let's say your mxml file's name is MyCanvas.mxml. You'd add this to another component using <ns:MyCanvas/> tag. You can set an id there and access it using that.

    <ns:MyCanvas id="myCanvas"/>
    

    Inside script:

    myCanvas.width = whatever;