模块是独立,通过继承接口,允许外部应用程序与他们通信。
首先,定义接口ICommunicaton.as:
package com.st.interfaces
{
public interface ICommunication
{
function getMessage():String;
function setMessage(value:String):void;
}
}
创建Module继承ICommunicaton接口:
<?xml version="1.0" encoding="utf-8"?>
<mx:Module xmlns:mx="http://www.adobe.com/2006/mxml" implements="com.st.interfaces.ICommunication">
<mx:Script>
<![CDATA[
import com.st.interfaces.ICommunication;
[Bindable]private var _value:String = "";
public function setMessage(value:String):void
{
_value = value;
}
public function getMessage():String
{
return _value;
}
]]>
</mx:Script>
<mx:Panel id="panel" title="Message:{_value}" width="400" height="200"/>
</mx:Module>
在Application通过ICommunication调用Module的方法(注意:不要用moduleLoader.child as (Module),这样就会把Module也编译进来):
var communication:ICommunication = moduleLoader.child as ICommunication;
communication.setMessage("loaded by app");
Application的代码:<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" minWidth="955" minHeight="600">
<mx:Script>
<![CDATA[
import com.st.interfaces.ICommunication;
import mx.containers.Panel;
import mx.modules.Module;
private const MODULE_URL:String="com/st/model/MyModule2.swf";
[Bindable] private var moduleLoaded:Boolean;
private function onModifyMessage():void
{
var communication:ICommunication = moduleLoader.child as ICommunication;
communication.setMessage("loaded by app");
var module:Module = moduleLoader.child as Module;
var panel:Panel = module.getChildByName("panel") as Panel;
trace(panel.title);
}
]]>
</mx:Script>
<mx:HBox>
<mx:Button id="btnLoad" label="Load Module" click="moduleLoader.loadModule(MODULE_URL)"/>
<mx:Button id="btnModify" label="Modify Model" click="onModifyMessage()"/>
<mx:Button label="Unload Module" click="moduleLoader.unloadModule()"/>
</mx:HBox>
<mx:ModuleLoader applicationDomain="{ApplicationDomain.currentDomain}" id="moduleLoader" y="30"/>
</mx:Application>