【问题标题】:Calling a function in an mxml file from outside从外部调用 mxml 文件中的函数
【发布时间】:2011-12-17 03:36:30
【问题描述】:

我有一个基本的 mxml 应用程序,看起来像这样

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" width="800" height="600">
<mx:Script>
    <![CDATA[


        public function init():void{

        }

这个 swf 使用 Loader 加载到另一个 swf 并使用 addChild(loader); 进行添加

然后我需要从父 swf 调用 init 函数。我怎样才能做到这一点? 只是打电话

loader.content.init();

失败。

另一个问题是,这个 mxml 文件的确切类名是什么?

谢谢!

【问题讨论】:

  • 你说,那个调用方法失败了。我们怎么知道它为什么会失败?向我们提供用于加载 swf 的错误文本和代码。
  • 确切的错误是:ReferenceError: Error #1069: Property init() not found on _Main_mx_managers_SystemManager 并且没有默认值。

标签: flash apache-flex actionscript mxml


【解决方案1】:

我建议使用接口而不是直接引用应用程序 mxml 的类。

  1. 定义一个接口:

    package behaviors {
        interface Initialiazable 
        {
            function init():void;
        }
    }
    
  2. 在应用mxml中实现接口:

    <?xml version="1.0" encoding="utf-8"?>
    <mx:Application implements="behaviors.Initialiazable"
        width="800" height="600"
        xmlns:mx="http://www.adobe.com/2006/mxml">
        <mx:Script>
            <![CDATA[
            public function init():void{
                trace("Application.init()");
            }
    
  3. 在其他应用程序中加载 SWF 应该是这样的:

    <?xml version="1.0" encoding="utf-8"?>
    <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
        <mx:Script>
        <![CDATA[
    
        import mx.events.FlexEvent;
        import mx.managers.SystemManager;
    
        import behaviors.Initializable;
    
        private var loadedApp:Initializable;
    
        protected function handleSWFLoaderComplete(e:Event):void
        {
            // wait for the Flex application to load
            var loadedAppSystemManager:SystemManager = e.target.content as SystemManager;
            loadedAppSystemManager.addEventListener(FlexEvent.APPLICATION_COMPLETE, handleApplicationComplete);
        }
    
        protected function handleApplicationComplete(e:FlexEvent):void
        {
            // cast the loaded application to the Interface
            loadedApp = (Initializable) e.currentTarget.application;
            loadedApp.init();
        }
        ]]>
        </mx:Script>
    
        <mx:SWFLoader source="LoadedApp.swf" complete="handleSWFLoaderComplete(event)"/>
    
    </mx:Application>
    

【讨论】:

  • 谢谢,但不幸的是,这失败并出现错误:TypeError: Error #1034: Type Coercion failed: cannot convert _Main_mx_managers_SystemManager@113720a1 to com.IInit.
猜你喜欢
  • 2015-03-02
  • 1970-01-01
  • 2013-07-28
  • 2017-02-19
  • 2019-02-10
  • 1970-01-01
  • 1970-01-01
  • 2019-01-23
  • 1970-01-01
相关资源
最近更新 更多