在外部的application中,需要监听module载入的事件,一旦有某个module载入,便要创建一个pipe来与该module通信。
监听的代码如下:
override public function handleNotification( note:INotification ):void
{
switch( note.getName() )
{
case ApplicationFacade.MODULE_ADDED:
connectModule( note.getBody() as IPipeAware );//note.getBody()得到的是加载进来的那个module的实例,这个module需要实现IPipeAware接口
break;
default:
super.handleNotification(note);
}
}
创建一个pipe使app与module通信:
public function connectModule( module:IPipeAwareModule ):void
{
// Register SHELL_TO_MODULE_PIPE from the shell to all modules
junction.registerPipe( PipeAwareModuleConstants.SHELL_TO_MODULE_PIPE,
Junction.OUTPUT,
new TeeSplit() );
// Register MODULE_TO_SHELL_PIPE to the shell from all modules
junction.registerPipe( PipeAwareModuleConstants.MODULE_TO_SHELL_PIPE,
Junction.INPUT,
new TeeMerge() );
// add a pipe listener for messages sended by module
junction.addPipeListener( PipeAwareModuleConstants.MODULE_TO_SHELL_PIPE,
this,
handlePipeMessage );
// module -> shell
var moduleToShell: Pipe = new Pipe();
module.acceptOutputPipe( PipeAwareModuleConstants.MODULE_TO_SHELL_PIPE, moduleToShell );//这一句就是将module连接到指定pipe上
var shellInFitting: TeeMerge = junction.retrievePipe( PipeAwareModuleConstants.MODULE_TO_SHELL_PIPE ) as TeeMerge;
shellInFitting.connectInput( moduleToShell );
// shell -> module
var shellToModule: Pipe = new Pipe();
module.acceptInputPipe( PipeAwareModuleConstants.SHELL_TO_MODULE_PIPE, shellToModule );
var shellOutFitting: TeeSplit = junction.retrievePipe( PipeAwareModuleConstants.SHELL_TO_MODULE_PIPE ) as TeeSplit;
shellOutFitting.connect( shellToModule );
}
上面两个方法即建立了app与 module之间的pipe。
来看module的代码,它要实现IPipeAware接口,所以要有以下两个方法:
public function acceptInputPipe( name:String, pipe:IPipeFitting ):void
{
facade.sendNotification( JunctionMediator.ACCEPT_INPUT_PIPE, pipe, name );
}
public function acceptOutputPipe( name:String, pipe:IPipeFitting ):void
{
facade.sendNotification( JunctionMediator.ACCEPT_OUTPUT_PIPE, pipe, name );
}
这里的facade是该module的facade,通过facade发送一个notification。这个notification会在
org.puremvc.as3.multicore.utilities.pipes.plumbing.JunctionMediator 中被捕获
部分代码如下:
// accept an output pipe
case JunctionMediator.ACCEPT_OUTPUT_PIPE:
var outputPipeName:String = note.getType();
var outputPipe:IPipeFitting = note.getBody() as IPipeFitting;
junction.registerPipe( outputPipeName, Junction.OUTPUT, outputPipe );
break;
注意junction.registerPipe这一句,会在module的mediator中注册一个pipe,这样app和module中就都注册了pipe,可以使用这个pipe进行通信了。
但这里就会有一个问题,正常流程如下:
app初始化完成-->加载module-->加载完毕-->触发事件,app开始建立pipe-->将pipe连接到module
不过有可能会先触发事件,使app建立完pipe后,才初始化module。这样在app建立pipe的时候,会调用
module的acceptOutputPipe方法,但这时module的facade还没有初始化,即发送的notification不能被捕获到,那么pipe便没有成功连接到module上,这样通信时就不会有反应。