Flex:从包含的组件中调用函数

3

这与我之前发布的帖子类似。但是这一次,我想调用存在于主mxml页面上的一个函数。

这是我的主mxml页面:

main.mxml

<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" xmlns:ns1="*">
    <mx:Script>
        <![CDATA[   
        public function changeText(currentText:String):void{

            switch (currentText){
                case "changeText":
                    lblOne.text = "More Text";                  
            }
        }
            ]]>
    </mx:Script>

    <mx:HBox x="137.5" y="10" width="100%" height="100%">
        <ns1:menu id="buttons"> </ns1:menu>
    </mx:HBox>
    <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"/>
            </mx:Panel>
        </mx:HBox>
    </mx:Canvas>
</mx:Application> 

以下是我的包含页面:
菜单.mxml
<?xml version="1.0" encoding="utf-8"?>
<mx:Canvas xmlns:mx="http://www.adobe.com/2006/mxml" width="400" height="300">
    <mx:Script>
        <![CDATA[
            [Bindable] public var showLabel:Boolean = true;
        ]]>
    </mx:Script>
    <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')}"/>
</mx:Canvas>

如何从menu.mxml中的按钮调用changeText函数?
2个回答

3
将此添加至菜单:
  <mx:Metadata>
         [Event(name="buttonClicked", type="flash.events.Event")]
    </mx:Metadata>

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

将主要内容更改为:

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

我无法确定当前文本的来源,但如果它来自菜单,则您可能需要构建自己的自定义 flex 事件或创建一个公共变量供两个部分访问。通常情况下,第一种方法更受欢迎。

附注:当应用程序创建完成时,也可以通过添加事件监听器来实现事件元数据。您可以将其添加到主文件中:

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

0

有一个更简单的方法,只需使用parentDocument。

将此更改为:

<mx:Button x="181" y="10" width="80" label="Run Function" id="btnThree" click="{changeText('changeText')}"/>

to:

<mx:Button x="181" y="10" width="80" label="Run Function" id="btnThree" click="{parentDocument*.changeText('changeText')}"/>**

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接