Flex Modules通信(1)——通过接口

     Flex Modules通信方式有很多种:通过继续接口、参数传递、定义事件通信。这里讨论通过继续接口通信。模块是独立,通过继承接口,允许外部应用程序与他们通信。

      首先,定义接口ICommunicaton.as:

1:  package
2:   {
3:      public interface ICommunication
4:      {
5:          function getMessage():String;
6:   
7:          function setMessage(value:String):void;
8:      }
9:  }

 

      创建Module继承ICommunicaton接口:

 1:  <?xml version="1.0" encoding="utf-8"?>
 2:  <mx:Module xmlns:mx="http://www.adobe.com/2006/mxml" implements="ICommunication" >
 3:      <mx:Script>
 4:          <![CDATA[
 5:              [Bindable]private var _value:String="";
 6:   
 7:              public function setMessage(value:String):void
 8:              {
 9:                  _value=value;
10:              }
11:   
12:              public function getMessage():String
13:              {
14:                  return _value;
15:              }
16:          ]]>
17:      </mx:Script>
18:      
19:      <mx:Panel id="panel" title="Message :{_value}" width="400" height="200"/>
20:  </mx:Module>
21:  

 

      在Application通过ICommunication调用Module的方法:

1:  var communication:ICommunication=moduleLoader.child as ICommunication;
2:  communication.setMessage("loaded by application");

    

      Application的代码:

 

 1:  <?xml version="1.0" encoding="utf-8"?>
 2:  <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
 3:      <mx:Script>
 4:          <![CDATA[
 5:              import mx.containers.Panel;
 6:              import mx.modules.Module;
 7:   
 8:              private const MODULE_URL:String="Module1.swf";
 9:   
10:              private function onModifyMessage():void
11:              {
12:                  var communication:ICommunication=moduleLoader.child as ICommunication;
13:                  communication.setMessage("loaded by application");
14:   
15:                  var module:Module = moduleLoader.child as Module;
16:                  var panel:Panel=module.getChildByName("panel") as Panel;
17:                  trace(panel.title);
18:   
19:              }
20:          ]]>
21:      </mx:Script>
22:      
23:      <mx:HBox>
24:          <mx:Button id="btnLoad" label="Load Module" click="moduleLoader.loadModule(MODULE_URL)" />
25:          <mx:Button id="btnModify" label="Modify Module" click="onModifyMessage()"/>
26:          <mx:Button label="Unload Module" click="moduleLoader.unloadModule()" />
27:      </mx:HBox>
28:      <mx:ModuleLoader id="moduleLoader" y="30"/>
29:  </mx:Application>
30:  

 

 

 

 

        运行结果,加载后点击Modify Module:

image

 

      注意:虽然使用继承接口实现Application和Modules通信很方便,实现接口就可以,但是在调用Modules方法是会锁定Modules内存,使用时得注意。

posted @ 2010-07-28 23:48  Asharp  阅读(2234)  评论(2编辑  收藏  举报