Actionscript – Flex: Call function from included component


This is similar to my previous posting. But this time I want to call a function that exists on the main mxml page.

This is my main mxml page:


<mx:Application xmlns:mx="" layout="absolute" xmlns:ns1="*">
        public function changeText(currentText:String):void{

            switch (currentText){
                case "changeText":
                    lblOne.text = "More Text";                  

    <mx:HBox x="137.5" y="10" width="100%" height="100%">
        <ns1:menu id="buttons"> </ns1:menu>
    <mx:Canvas x="137" y="88" width="408.5" height="200">
        <mx:HBox x="0" y="10" width="388.5" height="190">
            <mx:Panel width="388" height="179" layout="absolute">
                <mx:Label x="10" y="10" text="Some Text" visible="{buttons.showLabel}" id="lblOne"/>

Here is my included page:


<?xml version="1.0" encoding="utf-8"?>
<mx:Canvas xmlns:mx="" width="400" height="300">
            [Bindable] public var showLabel:Boolean = true;
    <mx:MenuBar width="380" height="58"></mx:MenuBar>
    <mx:Button x="10" y="10" width="80" label="Show" id="btnOne" click="this.showLabel=true;" />
    <mx:Button x="94" y="10" width="80" label="Hide" id="btnTwo" click="this.showLabel=false;"/>
    <mx:Button x="181" y="10" width="80" label="Run Function" id="btnThree" click="{changeText('changeText')}"/>

How do I call the changeText function from the button on menu.mxml?

Best Solution

Add this to menu:

         [Event(name="buttonClicked", type="")]

 <mx:Button x="10" y="10" width="80" label="Show" id="btnOne" click="this.showLabel=true;dispatchEvent(new Event("buttonClicked"));"/>

Change main to:

  <ns1:menu id="buttons" buttonClicked="changeText("Your Text");">

I couldn't tell where current text is coming from but if it is from menu you may have to build your own custom flex event or create a common variable for the two parts to access. The first is usually preferred.

P.S. The event metadata thing could also be achieved by adding the event listener when the creation of the application completes. You would add to main:

buttons.addEventListener("buttonClicked",changeText("Your Text"));