Flex Modules Watch Your Scope

Here’s another help hint for those working with Modules in Flex: Watch your variable scope!!

When loading modules, you have a number of options for loading the SWF including the ModuleLoader and ModuleManager. If neither of those fit your needs you always have access to Flash’s Loader class. ModuleManger can be used for fine grained control of the loading process. Either way, variable scope plays a crucial roll in the loading process.

Here’s an example using ModuleLoader…

public function loadSWFModule(swfURL:String):void
{
var moduleLoader:ModuleLoader = new ModuleLoader();
moduleLoader.url = swfURL;

moduleLoader.addEventListener(ModuleEvent.READY,onModuleLoaded);
moduleLoader.addEventListener(ModuleEvent.ERROR,onModuleError);
moduleLoader.addEventListener(ModuleEvent.PROGRESS,onProgress);
moduleLoader.loadModule();
}

The moduleLoader is declared as a local variable. As it turns out this will cause problems, even with the ‘strong’ event listeners. For those not wanting to read the technical details to follow, simply use avoid using a locally scoped variable.

The following are some of the symptoms you may run into using the latter locally scoped variable:

To help those searching the net, I’ll be a bit redundant in the ‘symptom’ descriptions so hopefully you’ll find this post if you’ve stumbled upon this problem

Symptons

  • The module fails to load the first time, but loads successfully the second time.
  • The ModuleEvent.READY is never dispatched
  • The ModuleInfoProxy never picks up the ModuleEvent.READY dispatched by ModuleInfo
  • ModuleInfo.clearLoader() throws an error (which is quietly caught), Error #2029: This URLStream object does not have a stream opened when calling loader.close()
  • The problem comes in when the Loader finishes loading the SWF. ModuleInfo’s internal listener list (listeners attached during ModuleInfoProxy’s constructor) are lost (i.e. null) when ModuleInfo finally reaches it’s readyHandler( ) method. At the end of the readyHandler( ), a ModuleEvent.READY event is dispatched.

    dispatchEvent(new ModuleEvent(ModuleEvent.READY));

    With the listener list being null, the event is never picked up by the ModuleInfoProxy and the initial load fails.

    On subsequent loads (i.e. the second time) ModuleInfoProxy’s load( ) method checks to see if the info has already been loaded and dispatches the ModuleEvent.READY event directly.

    else if (info.loaded)
    {
    //trace("Module[", url, "] load is already loaded");
    if (info.setup)
    {
    ...
    if (info.ready)
    {
    ...
    dispatchEvent(new ModuleEvent(ModuleEvent.READY));
    }
    }
    }

    Causing the load to ‘work’ the second time.

    My understanding is that Garbage Collection is often invoked when a module is loaded. It looks like it’s the cause of this behavior (the listeners being lost). I assumed that the ‘strong’ listeners would be enough to keep the GC away, oh well.

    Again the solution is simple, make sure your not using a locally scoped variable when loading modules.

    Pipe Demo: Mortgage App

    I’ve posted a pipes version of the mortgage app.

    Things to note:

    You can load / unload the modules dynamically.

    A junction mediator is defined for each ‘player.’ In the mortgage app context that’s a mediator for the application itself, the Acme widget and the Foo widget.

    ApplicationJunctionMediator
    ModuleJunctionMediator (Acme)
    ModuleJunctionMediator (Foo)

    To make our lives easier when it comes time to unload the module, the module caches the app’s pipe fitting it’s connected to. This allows the module to easily ‘cleanup’ (disconnect our fittings) should we want to unload the module. You may find a cleaner approach to this, feel free to post in comments – the ‘caching approach’ was simple and thus the road taken for the demo.

    Understanding PureMVC Pipes

    Disclaimer: This a bit of a longer post!!

    The pipes utility is newer to PureMVC and as such, I’ve seen questions on the blogosphere regarding it’s use.

    The plumbing metaphor should help wrap you head around this utility and it’s use. Keep in mind that a pipe allows for one-way message flow.

    So let’s take a look at how the utility can be used.

    One great features of ‘Pipes’ is that they can use used on top of an existing app. That is, you’ll simply need to define a JunctionMediator at/for each integration point.

    Let’s look at the simplest case, an application that loads and communicates with a module. We’ll assume that at some point you’ll want to use this same app to use multiple modules down the road. You’ll need to create a JunctionMediator for the application and a JunctionMediator for the module. We’ll dive into the details for those mediators but at a high level, that’s it – we simply define a ‘JunctionMediator’ for each ‘player.’

    Here’s a simple diagram

    Simple Pipe

    Our JunctionMediator’s will be connected together with pipes. We’ll have one pipe that allows for application-to-module message flows and another pipe that allows for module-to-application flows.

    On the receiving end of a pipe, we’ll want a pipe listener (you’ll have only one pipe listener for a given pipe). We’ll use pipe listeners to handle incoming pipe messages.

    To send messages down a pipeline, we’ll normally use the Junction’s ‘sendMessage’ function.

    Back to our simple example, our app’s JunctionMediator would be responsible for creating the app’s pipe fittings, creating pipes to connect to those fittings to the module.

    So the first thing our app’s JunctionMediator would do would be to create a new junction at creation.


    public class ApplicationJunctionMediator extends JunctionMediator
    {
    public function ApplicationJunctionMediator()
    {
    super(NAME, new Junction());
    }

    Once this mediator is registered with our facade, we’d want to create the PipeFittings. We’ll use a TeeSplit for outgoing and TeeMerge for incoming. The TeeSplit will allow us to connect to multiple modules for outbound messages. The TeeMerge will allow multiple modules to send messages up to our main app. We’ll also want to add a pipe listener on our TeeMerge. This listener will allow us to handle the messages being sent up from the modules to the app.


    override public function onRegister():void
    {
    junction.registerPipe( PipeAwareModule.APP_TO_MODULE_PIPE, Junction.OUTPUT, new TeeSplit() );
    junction.registerPipe( PipeAwareModule.MODULE_TO_APP_PIPE, Junction.INPUT, new TeeMerge() );
    junction.addPipeListener( PipeAwareModule.MODULE_TO_APP_PIPE, this, handlePipeMessage );
    }

    Our handlePipeMessage function is responsible for handling the messages coming up from our modules to our app.


    function handlePipeMessage(message:IPipeMessage):void

    Being a Mediator, we can define what application-level notifications we’re interested in and how to handle those notifications. That is, we’ll want to utilize listNotificationInterests() and handleNotification(note:INotification). We’ll use these to listen for notifications and turn desired notifications into messages to pass down our pipes.

    For example, our Mortgage App would listens for request for loan notifications and turn those notifications into messages.


    override public function handleNotification(note:INotification):void
    {

    switch( note.getName() )
    {
    case MortgageAppEventNames.REQUEST_FOR_LOAN:
    var loanMessage:Message = new Message(MortgageAppEventNames.REQUEST_FOR_LOAN,null,note);
    junction.sendMessage(PipeAwareModule.APP_TO_MODULE_PIPE,loanMessage);
    break;
    }
    }

    Our application JunctionMediator will also typically listen for a notification that a module has been loaded. Our app’s JunctionMediator will then create new pipes to connect the app’s junctionMediator to the modules junctionMediator. Something along the lines of…


    override public function handleNotification(note:INotification):void
    {

    switch( note.getName() )
    {
    case MortgageAppEventNames.REQUEST_FOR_LOAN:
    var loanMessage:Message = new Message(MortgageAppEventNames.REQUEST_FOR_LOAN,null,note);
    junction.sendMessage(PipeAwareModule.APP_TO_MODULE_PIPE,loanMessage);
    break;

    case ModuleEvents.CONNECT_MODULE_JUNCTION:
    var module:IPipeAwareModule = note.getBody() as IPipeAwareModule;

    // Create the pipe
    var moduleToApp:Pipe = new Pipe();
    // Connect the pipe to our module
    module.acceptOutputPipe(PipeAwareModule.MODULE_TO_APP_PIPE, moduleToApp);

    // Connect the pipe to our app
    var appIn:TeeMerge = junction.retrievePipe(PipeAwareModule.MODULE_TO_APP_PIPE) as TeeMerge;
    appIn.connectInput(moduleToApp);

    // Create the pipe
    var appToModule:Pipe = new Pipe();
    // Connect the pip to our module
    module.acceptInputPipe(PipeAwareModule.APP_TO_MODULE_PIPE,appToModule);

    // Connect the pipe to our app
    var appOut:TeeSplit = junction.retrievePipe(PipeAwareModule.APP_TO_MODULE_PIPE) as TeeSplit;
    appOut.connect(appToModule);

    break;

    // And let super handle the rest (ACCEPT_OUTPUT_PIPE, ACCEPT_INPUT_PIPE, SEND_TO_LOG)
    default:
    super.handleNotification(note);

    }
    }

    Finally our application’s JunctionMediator will handle the incoming pipe messages.


    override public function handlePipeMessage(message:IPipeMessage):void
    {
    // Handle our Module->Application integration
    trace(message);
    var note:INotification = message.getBody() as INotification;

    switch(note.getName())
    {
    case MortgageAppEventNames.LOAN_QUOTE_READY:
    sendNotification(note.getName(),note.getBody(),note.getType());
    break;
    default:
    sendNotification(note.getName(),note.getBody(),note.getType());
    break;
    }
    }

    That covers the basic responsibilities for our app’s JunctionMediator.

    Our module’s JunctionMediator would listen for messages coming in on the APP_TO_MODULE named pipe and send [outbound] messages on the MODULE_TO_APP pipe.


    override public function handleNotification(note:INotification):void
    {
    // Handle our Module->Application integration
    switch( note.getName() )
    {
    case ModuleFacade.QUOTE_GENERATED:
    // convert our *local* notification into the application format
    var quoteMessage:Message = new Message(MortgageAppEventNames.LOAN_QUOTE_READY,null,
    new Notification(MortgageAppEventNames.LOAN_QUOTE_READY,note.getBody(),note.getType()));
    junction.sendMessage(PipeAwareModule.MODULE_TO_APP_PIPE,quoteMessage);
    break;
    }
    }

    override public function handlePipeMessage( message:IPipeMessage ):void
    {
    // Handle our Application->Module integration
    var note:INotification = message.getBody() as INotification;
    switch(note.getName())
    {
    case MortgageAppEventNames.REQUEST_FOR_LOAN:
    sendNotification(ModuleFacade.QUOTE_REQUESTED,note.getBody(),note.getType());
    break;
    }

    }

    If the app was to load another module our diagram would become…
    Pipes App with Two Modules

    If your still have questions – just ask 🙂

    Loaded Module Dimensions – Width / Height

    Ran across a problem regarding the display size of dynamically loaded modules today. The module was a subclass of ModuleLoader. The module would size to the minWidth / minHeight I had specified but would ignore width=”100%” for height=”100%”.

    This Adobe Tech note states that your module should use ‘percentWidth’ and ‘percentHeight.’ I set that for the module and still no luck (probably because I subclassed ModuleLoader not Module for the time being).

    What did work was to set the percentWidth / percentHeight in actionscript before I call addChild().


    module.percentHeight = 100;
    module.percentWidth = 100;
    this.addChild(module);

    Pipe Architecture

    Here’s a working architecture for modular applications utilizing PureMVC pipes.

    Pipe Architecture

    This allows you to have modules that load modules that load modules, etc. The modules communicate to each other via Pipes.

    The sample diagram illustrates a parent, child, grandchild relationship (An app that loads a module that loads module). You can of course, have multiple siblings.

    PureMVC Pipes

    I had a chance to work with Cliff Hall’s PureMVC ‘Pipes’ utility this week. Highly recommended.

    If your interested in utilizing modules in your PureMVC projects, you owe it to yourself to take a look at the Pipes utility.

    What’s needed to integrate a module?

    The requirements are very light. You module should:

    Implement IPipeAware
    Create a JunctionMediator.

    Thats it.

    I took some time and refactored the Mortgage app to use the Pipes utility.

    I ran into a small bump after unloading widgets. If I unloaded a widget and then clicked “Quotes”, I still received a loan quote from what should have been an unloaded module. I ended up subclassing the ‘TeeSplit’ class to allow disconnecting a single known IPipeFitting. This allowed me to ‘cleanup’ the dynamic modules properly.

    That aside, the utility was very easy to work with – the plumbing metaphors really make things clear.

    I found the utility to be quite flexible as well. I just wrapped up working on some utility classes that allow modules to load modules that load modules etc. Getting this to work with direct core to core communications was at best ‘messy.’ Using the pipes made this very clean and simple.

    PureMVC + Lazily [late] Instantiated Components

    One small caveat when working with PureMVC – If your [view] component is defined at design time, but not created at application startup you’ll need to defer the

    facade.registerMediator( )

    This might happen, for example, when your component resides in a viewstack.

    A simple work around is to dispatch an event (make sure it bubbles) on the component’s creationCompelete.

    creationComplete="dispatchEvent(new Event(CommonEvents.COMPONENT_INITIALIZED,true))"

    In the ‘application level’ mediator, create an event listener for this event

    viewComponent.addEventListener(
    CommonEvents.COMPONENT_INITIALIZED,onComponentReady,false,0,true);

    When the event is picked up you’ll have to determine which [lazy] component is ready

    public function onComponentReady(event:Event):void
    {
    var comp:UIComponent = event.target as UIComponent;

    switch(comp.id)
    {
    case "userSearch":
    facade.registerMediator(new UserSearchMediator(comp));
    break;
    case "serviceRecord":
    facade.registerMediator(new ServiceRecordMediator(comp));
    break;
    case "appToolbar":
    facade.registerMediator(new AppToolbarMediator(comp));
    break;
    }

    }

    So, in short, we simply defer creating the component’s mediator until the view component is ready 🙂

    AS3 PureMVC Dynamic Modules

    Okay, I’ve had some questions on refactoring my PureMVC dynamic modules classes to support AS3 projects (i.e. no flex).

    I’ve posted a sample app that does just that.

    I threw this together off the cuff, so don’t expect too much 🙂

    The app (10K) simply loads 6 modules dynamically, 3 “RedTint” modules and 3 “GreenTint” modules (4k each). The app sends a notification every second containing a random color. The loaded modules pick up on this notification and display the color – each with their corresponding tint.

    Keep a close eye on Cliff’s Pipe utility as these classes may soon be obsolete 🙂 Until that time, I hope you might find this useful – if you do, drop me a line and let me know.

    I’ve got some time between projects if anyone is looking for some RIA development…

    Dynamic Modules … General Tips

    Okay, for those of you getting ready to work with dynamic modules, I thought I’d share a few minor points I picked up on this past week.
    Your application must include a reference to any interfaces the module implements.

    <mx:Moudule implements"com.company.project.SomeInterface">

    You’d want a reference to com.company.project.SomeInterface in your main app.
    Likewise if the module has subclassed Module

    public class MyModule extends Module

    You’ll need a reference to MyModule in your main app as well.

    There are compiler options to include these references, however I find it easiest to just declare a variable of the corresponding type.

    i.e. var interfaceDef:ICustomInterface

    If you find yourself wanting to create your own ‘View’ class in PureMVC it’s pretty straightforward. Just ensure that you subclass the controller as well.

    Here’s a sample facade utilizing a custom view class…

    protected override function initializeController( ):void
    {
    if ( controller != null )
    return;
    controller = CustomController.getInstance( multitonKey );
    }

    // Our custom View subclass in action
    protected override function initializeView( ):void
    {
    if ( view != null )
    return;
    view = CustomView.getInstance( multitonKey );
    }

    And the custom controller…

    public static function getInstance( key:String ) : IController
    {
    if ( instanceMap[ key ] == null )
    instanceMap[ key ] = new CustomController( key );
    return instanceMap[ key ];
    }

    override protected function initializeController( ) : void
    {
    view = CustomView.getInstance(multitonKey);
    }

    Finally, our custom View

    public static function getInstance( key:String ) : IView
    {
    if ( instanceMap[ key ] == null )
    instanceMap[ key ] = new CustomView( key );
    return instanceMap[ key ];
    }

    In practice the view in initialized in the controller’s initializeController() method, so without subclassing your Controller you still maintain the standard View.

    Dynamic Flex Modules with PureMVC

    I’m rolling out a large project, and I wanted to utilize dynamic modules for scalability.

    For those who aren’t familiar will modules, basically, there a great way to encapsulate “pieces” of your application. A trivial example would be a small ‘shell application’ that once the user logs in, loaded the appropriate use-case module. If your working in a team environment modules make for an easy project divide-and-conquer approach.

    I’ve been using the PureMVC framework lately and figured adding support for dynamic modules wouldn’t be too difficult as Cliff and the gang have already been hard at working getting the framework changes in place to make this possible (replacing singletons with multitons etc).

    Well after some working laying this out, I’m glad to say I’ve got it working. Check out this sample app Dynamic Mortgage Demo.

    The demo allows the user to get loan quotes from [fictional] banks. The demo allows the user to dynamically load / unload bank “modules.”

    The application and modules are very well encapsulated. Here’s whats required from each party…

    Application:

    Must compile with…

    A reference to any interfaces the modules loaded at runtime implement (ILoadableModule in our case).

    A reference to any subclasses of mx:Module the modules are using (PureMVCLoadableModule in our case). This is only necessary if your subclassing mx:Module.

    That’s it.

    Here’s the integration point on the modules end…

    The modules facade implements an “InitializeMapping” function which maps application notification names to local (module) notification names [inbound mapping]. The function also defines module notification name to application notification name [outbound] mappings.

    Here’s an example

    override public function initializeMappings():void
    {
    outboundMappings:Array = new Array();
    outboundMappings[QUOTE_GENERATED] = EventNames.LOAN_QUOTE_READY;

    inboundMappings = new Array();
    inboundMappings[EventNames.REQUEST_FOR_LOAN] = QUOTE_REQUESTED;
    }

    And thats the extent of what our application and modules know of each other. The rest of the ‘work’ is done automatically by a few interfaces / subclasses I wrote on top of PureMVC to make this possible. (i.e. your modules facade subclasses ModuleFacadeBase etc). No framework changes we’re required just some subclassing here and there.