Splitting Flex application into modules

There are many scenarios in which you might want a part of the code in Adobe Flex application to be loaded only when required, that is you might not want a piece of code to be compiled into main application SWF, instead load it when required. Scenarios can include screens which user accesses very rarely or a set of libraries which you want to load when required. This can achieved using Modules in Flex.

There might be many screens in Adobe Flex application, which user access very rarely. Examples can include screens where users give suggestions, complaints etc. if all such screens are included in your application, your application size might be huge, affecting the initial loading experience.

Similarly you might have a library code which might be used rarely. Examples can include library for creating reports, which is required only when the user wants the reports to be generated.

All such code which you think will be used very rarely can be included in modules and load them dynamically when required.

About modules

Modules are SWF files which can be loaded dynamically by an application. They cannot run independently, they have to be invoked by application. Any number of applications can share the same module.

Modules allow you to interact with the parent application and also interact with other modules. Modules can be loaded either using ModuleLoader or ModuleManager.

Click here for more details on Modules

Sample application

This application shows how to load a module dynamically. The module loaded dynamically will display a window in which we can capture user’s suggestions. The module accepts input from the parent application and also invokes properties of the parent application.

Application includes three files.

Modules.mxml – this will invoke the module

SuggestionModule.mxml – this is the module

IUserInput.as – this interface is implemented by the module. This is for module-application communication. (Optional)

Screen shot

Modules Sample Application

Modules.mxml

<?xml version=”1.0″ encoding=”utf-8″?>

<mx:Application xmlns:mx=”http://www.adobe.com/2006/mxml&#8221; layout=”vertical”>

<mx:Script>

<![CDATA[

import mx.controls.Alert;

import mx.managers.PopUpManager;

import mx.events.ModuleEvent;

import mx.modules.ModuleManager;

import mx.modules.IModuleInfo;

private var moduleInfo:IModuleInfo;

private var suggestion:SuggestionModule;

private function loadSuggestionModule():void

{

moduleInfo = ModuleManager.getModule(“SuggestionModule.swf”);

moduleInfo.addEventListener(ModuleEvent.READY, renderSuggestionModule);

moduleInfo.addEventListener(ModuleEvent.ERROR, handleError);

moduleInfo.addEventListener(ModuleEvent.PROGRESS, showProgress);

moduleInfo.load();

suggestionProgress.visible = true;

}

private function renderSuggestionModule(event:ModuleEvent):void

{

suggestion = moduleInfo.factory.create() as SuggestionModule;

suggestion.setHeaderMessage(“Suggestion – Home Page”);

PopUpManager.addPopUp(suggestion, this, true);

PopUpManager.centerPopUp(suggestion);

suggestionProgress.visible = false;

}

public function closeSuggestion():void

{

PopUpManager.removePopUp(suggestion);

moduleInfo.unload();

}

private function showProgress(event:ModuleEvent):void

{

suggestionProgress.text = “Loaded ” + Math.round((event.bytesLoaded / event.bytesTotal)* 100) + “%”;

}

private function handleError(event:ModuleEvent):void

{

Alert.show(event.errorText,”Error”);

suggestionProgress.visible = false;

}

]]>

</mx:Script>

<mx:Button id=”chartModuleBtn” label=”Suggest” click=”loadSuggestionModule();”/>

<mx:Label id=”suggestionProgress” text=”Loaded 0%” visible=”false”/>

</mx:Application>

SuggestionModule.mxml

<?xml version=”1.0″ encoding=”utf-8″?>

<mx:Module xmlns:mx=”http://www.adobe.com/2006/mxml&#8221;

layout=”vertical” width=”366″

height=”200″ borderStyle=”solid” cornerRadius=”11″

borderColor=”#000305″ borderThickness=”2″

implements=”com.adobe.IUserInput”>

<mx:Script>

<![CDATA[

import mx.controls.Alert;

[Bindable]

private var heading:String = “Your suggestion please”;

private function submitSuggestion():void

{

parentApplication.suggestionProgress.text = “We will consider your suggestion”;

parentApplication.suggestionProgress.visible = true;

parentApplication.closeSuggestion();

}

public function setHeaderMessage(message:String):void

{

this.heading = message;

}

]]>

</mx:Script>

<mx:Form width=”100%” height=”100%”>

<mx:FormHeading label=”{heading}”/>

<mx:FormItem label=”Your Name”>

<mx:TextInput id=”userName” width=”233″/>

</mx:FormItem>

<mx:FormItem label=”Suggestion”>

<mx:TextArea id=”description” width=”234″/>

</mx:FormItem>

<mx:ControlBar width=”100%” horizontalAlign=”center”>

<mx:Button label=”Submit” click=”submitSuggestion();”/>

<mx:Button label=”Cancel” click=”parentApplication.closeSuggestion();”/>

</mx:ControlBar>

</mx:Form>

</mx:Module>

IUserInput.as

package com.adobe

{

public interface IUserInput

{

function setHeaderMessage(message:String):void;

}

}

57 Responses to Splitting Flex application into modules

  1. Peter Witham says:

    Thank you so much for this post, the module idea in Flex was giving me problems getting my head around but this post really makes it clear, and also explains why it’s so useful!

    Regards,
    Peter Witham

  2. Sujit Reddy G says:

    Hi Peter,
    Thanks for the comments. Module is a great feature of Flex. There is another one called RSL in FLex, which can also be very useful. I will blog about RSL soon🙂

  3. Peter Witham says:

    I look forward to it, I’m still getting my head around the move from Flash Pro to Flex. But it’s all good fun🙂

  4. Nice post,
    I have one problem. I am loading Module inside my main application and then inside that module I want to navigate from one canvas to another. Like in HTML if I click on a hyper link, all screen gets clear and the html content of another page is loaded. But in flex I want to persist my Shell and navigate to another canvas. I know its a small thing, but I am missing it. Please help me in it.

    Thanks

    Chetan

  5. Sujit Reddy G says:

    Hi Chetan,

    You can try navigator containers or view states. Below are the URLs to the tutorials.
    http://livedocs.adobe.com/labs/flex3/html/navigators_1.html
    http://livedocs.adobe.com/labs/flex3/html/using_states_1.html
    Let me know if this helps🙂

  6. jurlan says:

    First of all apologies if this leads to an endless discussion, or maybe it’s just a silly question, but I’ll go ahead anyway ..

    I’m building a crm kind-of application. For now there are 2 parts: Customers and Products .. Would it be wise to make the Customers.mxml and the Products.mxml (which each have sub-pages and are now components) modules which only get loaded when a user clicks one of the 2 items on the main navigationbar?

    I know there are discussions about this all around, but since I really enjoy this blog and visit it daily I thought I’d stick to it😉

    Thanks in advance
    //jurlan

  7. Sujit Reddy G says:

    Hi Jurlan,

    Great to know that people are reading my blogs regularly🙂 Thanks🙂

    You can obviously modify them to modules and load then only when required. If you have them as modules, there is a time lag when the user clicks because the module has to be loaded from the server.
    If they are components then they are loaded with the intial SWF and so if the components are heavy then there is a time lag in the initial load.

    Now you can decide what you want to do🙂

    Hope this helps.

  8. jurlan says:

    Hi!

    Thanks for the reply😉
    I guess I’ll make my user wait at startup and present them with a nice preloader, because if they have to wait during clickevents they might think I did bad coding😉

  9. Sujit Reddy G says:

    Great🙂

  10. Glen Black says:

    When I load modules, I use the Application.application.enabled property and CursorManager.addBusyCursor function to make the application look like it’s doing something important. Then, when I get the READY or ERROR event, I clear those.

    In the meantime, I use a timer to pop up a custom window with a progress bar if the loading takes more than 7 seconds. The “I’m adding that functionality to the application…” caption almost makes a user happy to wait. 🙂

  11. Prasad says:

    I have a question– i have a main Application that has some icons. on clicking an Icon, i want to send a HTTP POST and the response of that would contain a Module name. I want to parse that and load the Module.

    And each Module can have some components and buttons, and clicking on the button could send another HTTP request and that can return another Module Name..etc..

    Also can the Module interact with the parent application — eg – to send the http request.. i want to use common code for that.
    I was wondering whether i can do this with FLEX and Action Script?
    Thanks in advance
    prasad

  12. Sujit Reddy G says:

    Hi Prasad,

    You can definitely do this.

  13. YogiFish says:

    This information is great. I’m building a social application with various views/pages. I see that modules would be the best way to setup the interaction.

  14. shubham says:

    hi sujit,
    hw r u???u might not remember but i met you in hyderabad when you at satyam(Flex boot camp)…Since then i m trying my hands on flex and m njoying it a lot..

    I have a query i want to display my data in pages..for example a scrapbook has many messages now if i want to display 10 messages at a time and give a next or previous button to see the next 10 messages..how can i do it????

  15. shubham says:

    and yes i forgot to say..your share market app looks great..can you share the code with me on my email id:escortnotice@gmail.com……

  16. Hi Shubham,

    Thanks🙂 I will share that code soon on my blog. If you want to load all the data on the client and display in multiple views you just have to store the data in a ArrayCollection or Array and display only required. If you want fetch the data from the server as when user navigates to different pages, you will have to modify your back end code to support this and invoke the service when required to get the data for a page.

    Hope this helps.

  17. Priyank says:

    Awesome blog with helpful contents. Just a thought, can i use a module between different application hosted in different locations. ie. I have a module called “A”, and have two applications “B”, and “C”, and both the applications use the module “A”.. Is there anything else i can use here?

  18. shubham says:

    Hi sujit.Thanks for the suggestion.I am able to display it in a data grid.
    I have another query..its not flex..but i hope you can help me.I am trying to build a search facility for a website(JAVA).which can index my website and answer to the users query.I dont want to use the like query is there any other option.I have heard abt hibernate search and lucene but not finding enough material on net to start with.If its possible for u then please do guide me with this…

  19. Hi Priyank,

    You can load a module from a different domain. Make sure the cross domain policy file is present.

    Hope this helps.

  20. Babji Reddy says:

    Hi Sujit
    I have a Flex mxml application that gets a user defined XML from a HttpService.
    For example a snippet of the XML is

    In the MXML when I am rednering the and using a Repeater on the Widgets list, how can I do a nested if/else (or switch-case ) like statement to render different UI FormItems?

    Thanks

  21. Babji Reddy says:

    sorry Sujit, when I entered the actual XML characters in this “comment form”, the XML didn’t show up in first time.
    I am trying to add the XML now with encoding the characters
    <Widgets>
    <Widget type=”text” name=”first name” width=”30″ />
    <Widget type=”date” name=”date of birth />
    ..
    </Widgets>

  22. Hi Babji,

    Try any of the List/Tile based components.

    Hope this helps.

  23. Henry says:

    Folks, I’m new to Flex so forgive my lack of knowledge. I’m setting up a data entry application that has many different screens. I was looking at setting up the handling of each screen in a module. Since one screen can cause another screen to be displayed, I’ve in-effect created a screen hierarchy or a nesting. In reading the manual I got the impression that modules can’t load other modules. Is that true? If so, any suggestions on how to structure something like this?

  24. Manan says:

    Hi,Sujit..

    i must say nice blog n comments,i got nice knowledge regarding the modules..

    m developing chatting application..i’m having 3modules in my application,loginpage and registrationpage..n 3rd 1 is the application which does chatting..all is set,the only problem is when i click the SignIn button on my login page,i want to nevigate to the user’s home page,(i.e. 3rd module)..how can i get it??

    inshort,i’ve 4 mxml files..main app file n 3modules..i wanna nevigate from my 1st module to 3rd module wen i press a button in my 1st module..will custom events help??

  25. Hem Talreja says:

    Sujit,

    I’m having an interesting issue.

    I have a button that triggers the loading of a module and adds the module as a child into a TabNavigator.

    I have to click the button twice the first time to load the module, and one after the first time….

    public function loadModule(event:Event):void
    {
    var _module:IModuleInfo = ModuleManager.getModule("view/HomeScreen.swf");

    _module.addEventListener(ModuleEvent.READY, loadModule_readyHandler);
    _module.addEventListener(ModuleEvent.ERROR, loadModule_errorHandler);
    _module.addEventListener(ModuleEvent.PROGRESS, loadModule_progressHandler);
    _module.addEventListener(ModuleEvent.SETUP, loadModule_startHandler);

    trace("loading module" + _module.url)

    _module.load(ApplicationDomain.currentDomain, SecurityDomain.currentDomain);
    }

    private function loadModule_startHandler(event:ModuleEvent):void
    {
    trace("setup!!!");
    }

    private function loadModule_readyHandler(event:ModuleEvent):void
    {
    trace("Module Loaded");

    var _module:IModuleInfo = event.target as IModuleInfo;
    var _displayComp:DisplayObject = _module.factory.create() as DisplayObject;

    vs.addChild( _displayComp );
    }

    private function loadModule_errorHandler(event:ModuleEvent):void
    {
    var _module:IModuleInfo = event.target as IModuleInfo;

    trace("Error Occured!");
    }

    private function loadModule_progressHandler(event:ModuleEvent):void
    {
    trace("Progress: " + (event.bytesLoaded / event.bytesTotal ) * 100 );
    }

  26. Hem Talreja says:

    Henry,

    Can can look into using Universal Mind Extensions with Cairngorm.

  27. Keerthika says:

    Hi,
    Can someone please help me out here?
    My org is using using flex for front end. we have 2 different front ends which looks exactly the same but serve different purposes. so using view states for that. now i need to develop a 3rd front end which is 70% the same, but need to add a couple of extra columns here and there and a couple of extra popups. i was wondering if its possible using modules, to use the common part of the application, and add the required extra columns and popups only in my module? using modules, can we get as granular as that? okie! hope i get a solution soon! thanks in advance!

  28. Hi Henry,

    You can load a module from another module. If you think the modules will anyways load and the user has to wait till the modules are loaded, don’t go for a module, keep the screens in the main application itself. Please visit the URL below for details.

    http://opensource.adobe.com/wiki/display/flexsdk/Marshall+Plan

    Hope this helps.

  29. Hi Manan,

    Please find details on how to load modules at the URL below.

    http://livedocs.adobe.com/flex/3/html/modular_5.html

    Hope this helps.

  30. Hi Hem,

    Please try making changes show below.

    private var _module:IModuleInfo;
    public function loadModule(event:Event):void
    {
    _module = ModuleManager.getModule(“Module1.swf”);

    _module.addEventListener(ModuleEvent.READY, loadModule_readyHandler);
    _module.addEventListener(ModuleEvent.ERROR, loadModule_errorHandler);
    _module.addEventListener(ModuleEvent.PROGRESS, loadModule_progressHandler);
    _module.addEventListener(ModuleEvent.SETUP, loadModule_startHandler);

    trace(“loading module” + _module.url)

    _module.load();
    }

    Hope this helps.

  31. Hi Keerthika,

    You can do this using modules, but looks like creating a custom component and having it in the main application seems to be a better solution in your case than loading a module. Modularize your component if you think that view will be used very rarely or want to make the initial load of the application faster by loading the component later.

    Hope this helps.

  32. lanc says:

    Getting this below error when i run mxmlc module.mxml in the command prompt

    Error: Type was not found or was not a compile-time constant:TideFaultEvent

    How could that possibly due to?

  33. Vijay says:

    Hi,

    I should say this is nice blog, as i ref
    I dont understand how to Authorize my CustomerService Application.
    Actually This Application is divided into several parts and these are interacting in between them.These parts are not modules as of now, they are components only in my application.
    Depending on the login credentials,some components should be activated, even some fields in that components should not be in active state for that user.

    Can someone help me out ?Hoping the reply soon

    Thanks.

  34. jason b says:

    lanc,

    you need to add in this to your script tag
    import mx.modules.*;

  35. Hi Lanc,

    Looks like you have TideFaultEvent referenced in your module.mxml file, please make sure it is found by the compiler as Jason mentioned.

    Hope this helps.

  36. Hi Vijay,

    Since you don’t have the views as modules, they are already loaded in the SWF file. I would have stored list of allowed views for a particular role on the server and load the list when the user logs in. Depending on the list, you can show/hide views for a user.

    Hope this helps.

  37. Somu says:

    Hi sujit,
    i have one issue that,
    i have 2 module and i want to dispatch a custom event from one module and catch in 2nd module.
    but because of some reason i am not able to catch the event in 2nd module.
    can you please help me and pointed out the problem?

    Thanks
    Somu

  38. John says:

    If you directly reference your module class (SuggestionModule,mxml) within the application that is loading it (Modules.mxml), that class gets compiled into your main application SWF. This defeats the purpose of using modules to incrementally deliver content.

    In doing this your SuggestionModule class and the classes it references are compiled into both the main application SWF and the SuggestionModule.swf.

  39. Porter says:

    Sujit and other experts,
    I’m doing a large application and doing some thinking on splitting code/functionality between modules. Looks like this is the forum where I can look forward for an answer to my question.

    My UI will change a bit (80% common) depending on user Role ad will provide different functionality on mouse and keyboard events to different roles. How can I have this code split into different modules incrementally.
    For library functions its easy to split, but for UI it’s tricky. I do not want to have 5 modules for 5 different roles which have 80% common stuff.

    Will appreciate your thoughts on this.

  40. abhishek says:

    great example friend,🙂

  41. Sergey says:

    Hi,Sujit..
    in addition to your code examples
    As I see, you don’t use module interface at all, and the main application invokes setHeaderMessage() module method with using factory property and casting to SimpleModule, right? i.e. the module instance is used here to call module’s methods.
    Think, IUserInput interface and ModuleLoader using might be more useful in that case to avoid so-called hard dependencies between the module and the application.
    something like that:
    var isuggestion:* = mod.child as IUserInput;
    isuggestion.setHeaderMessage(“Suggestion – Home Page”);
    where mod is an instance of ModuleLoader
    Then we can implement interfaces for the application as well so that to invoke methods of the application from the module (if it’s really needed)
    what do you thinks about this approach?

  42. Sateesh says:

    Hi Sujit,
    I have an existing application. This each view shares data with in the app. Say, the Greetings tab canvas shares data in Main Tab canvas. Can u please tell me how to convert it into modules. Like Guest Module, User Module, Shopping Cart Module etc., so that these data connections/ relations wont be affected.

  43. Glen says:

    Hi Sujit,

    As this blog is active, I thought of posting my question here regarding module loading/unloading memoryleak issue.
    http://forums.adobe.com/thread/435631
    The detailed question is given in this link. I dont think there is any concrete answer given by Adobe on this. Do you have any workaround?

  44. Kannan says:

    Hi Sujit,

    I am using modules, but i get a error , when multiple modules are loaded quickly. or some time when I Try to load the first module.

    TypeError: Error #1009: Cannot access a property or method of a null object reference.
    at ModuleInfo/completeHandler()[C:\autobuild\3.3.0\frameworks\projects\framework\src\mx\modules\ModuleManager.as:717]

    I found a bug was registered
    http://bugs.adobe.com/jira/browse/SDK-20753
    but I am not clear about the fix. please help
    Thanks

  45. Dave says:

    Hi,

    I am currently working on a project using flex 3 and weblogic server 10.3.
    I came across ur article on building flex modules, and thought that my project could use it.
    However i am not able to figure out, how i could deploy the individual .swf files onto my weblogic server.
    I have only one experience in building a flex application. and for that, i was using blazeds and java, and the single swf file was being wrapped into a html page and compiled into a .ear file before deploying onto my server.
    Hence upon coming across the concept of modules, i couldnt figure out how i could actually deploy theses modules onto my web server, and loading them in the shell application

    Pls help
    Thanks in advance

  46. Karan says:

    Hi ,
    I need some urgent help.
    We load a module from the parent application. When we deply the application on local server and run the module, the UI is perfect. BUT, when we deploy the application on our distant unix dev server, the module loads fine and fetches all date, BUT — the UI is distorted.By distorted I mean that if I scroll up /down/left/write the the page display breaks as if the page is not refreshed. The page looks scrambled.
    Then I noticed that when I hit the dev URL in Internet explorer, the module UI is distorted. But , when I hit the dev URL in firefox, the UI is perfect.

    Note : there are lots of repeaters and other such components used in the module.

    Please help!!

  47. Shreyas says:

    Hey Porter, did you get any answers on how to proceed?

    I have a similar requirement (Hope you see this comment)

  48. pms_11 says:

    can any one help us to create a login page using flex and LCDS(how to insert and retrieve data from mysql database) ?

  49. Sergey says:

    Hi pms_11,
    you can use HTTPService componens for flex frontend and some web service (PHP or jsp page for example) as web backend that would retrieve data from mysql database.
    Here the example how it can be done http://livedocs.adobe.com/flex/3/html/help.html?content=data_access_1.html

  50. Deepak says:

    It is a nice sample. One of the question is how to drive this via a configuration file. Meaning if the config is changed swf is loaded otherwise not. That would be a super example for building configurable applications

  51. Deepak says:

    Hi,

    I have a problem using modules in FLEX builder 3. We have a AIR application project which creates an swf file and we have another project which creates a swc file which is what is used by the AIR application. When I create a module in the the project which is creating the swc file I see it being added to the project. I also can see it catalog.xml file part of the swc file. But when I try to load it from one of the controls in the swc file I get the following error.

    Error #2035: URL Not Found. URL: app:SuggestionModule.swf

    The question I have is first of all I do not see any SuggestionModule.swf file any where. I am assuming it is created on demand. If that is so then why is it not being found. It is also not clear whether the FLEX builder 3 as it encounters the module directive in a module file creates the swf file if it is true where does it get written.

    I can create the swf file using the mxmlc command but I do not want to do it as I need to understand why the IDE is not doing what should be a simple one step process.

    My question is can we create a new module using the file new (module) wizard. Then add code to it. Then invoke it anywhere using the loadmodule. Is there any path or root path we have to take care.

    Any help or suggestion on how one trouble shoot the path problem would be useful for the community.

  52. andflex says:

    who have some problem with profiling module with text input inside..????? like me??

  53. who have some problem with profiling module with text input inside..????? like me??

  54. Reddy says:

    Hi Sujit,

    I am big fan of your blog. Nice useful articles and examples to support them.

    I have one problem with the modules example. My module loads fine without any issues. One issue which I am facing is the Error #1069: Property closeSuggestion not found on Modules and there is no default value, occurs when I click the submit button on the module component. Any idea what wrong I am doing? Do I need to write a closeSuggestion() function?

    Thanks in Advance

  55. Anil says:

    Hi Sujit,
    We have a AIR desktop client which talks to a WAMP server. We want to convert it to Flex app that can be used from the browser. How do i approach changing it?

    Thanks
    anil

  56. thanks for sourcecode,It’s useful

  57. Hi Anil,

    You can create a web application and import the existing project files into the new one. You might have to change the root application WindowedApplication. If you have any code that uses AIR specific APIs, you need to change the same.

    Hope this helps.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: