Actionscript – How to call a MXML class in ActionScript3.0 in Flex 3

actionscriptflex3mxml

I have a page made of custom components. In that page I have a button. If I click the button I have to call another page (page.mxml consisting of custom components). Then click event handler is written in Action-script, in a separate file.

How to make a object of an MXML class, in ActionScript? How to display the object (i.e. the page)?

My code:

page1.mxml

<comp:BackgroundButton x="947" y="12" width="61" height="22" 
      paddingLeft="2" paddingRight="2" label="logout" id="logout"
      click="controllers.AdminSession.logout()"
 />

This page1.mxml has to call page2.mxml using ActionScript code in another class:

static public function logout():void {
   var startPage:StartSplashPage = new StartSplashPage();
}

Best Answer

Your Actionscript class needs a reference to the display list in order to add your component to the stage. MXML is simply declarative actionscript, so there is no difference between creating your instance in Actionscript or using the MXML notation.

your function:

static public function logout():void {
   var startPage:StartSplashPage = new StartSplashPage();
}

could be changed to:

static public function logout():StartSplashPage {
   return new StartSplashPage();
}

or:

static public function logout():void {
   var startPage:StartSplashPage = new StartSplashPage();
   myReferenceToDisplayListObject.addChild( startPage );
}

If your actionscript does not have a reference to the display list, than you cannot add the custom component to the display list. Adding an MXML based custom component is no different than adding ANY other DisplayObject to the display list:

var mySprite:Sprite = new Sprite();
addChild(mySprite)

is the same as:

var startPage:StartSplashPage = new StartSplashPage();
myReferenceToDisplayListObject.addChild( startPage );

Both the Sprite and the StartSplashPage are extensions of DisplayObject at their core.

You reference MVC in the comments to another answer. Without knowing the specific framework you've implemented, or providing us with more code in terms of the context you are trying to perform this action in, it is difficult to give a more specific answer.

Related Topic