Search code examples
flashapache-flexactionscriptmxml

Calling a function in an mxml file from outside


I have a basic mxml app which looks like this

<?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{

        }

this swf is loaded into another swf using Loader and added with addChild(loader);

i then need to call the init function from the parent swf. how can i do this? just calling

loader.content.init();

fails.

another question is, what is the exact classname of this mxml file?

thanks!


Solution

  • I would suggest using an interface instead of directly referring to the class of the application mxml.

    1. Define an interface:

      package behaviors {
          interface Initialiazable 
          {
              function init():void;
          }
      }
      
    2. Implement the interface in the application 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. Loading the SWF inside other app should be something like this:

      <?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>