Example Of Using Modules In Flex 2.01

Flex 2.01 includes support for modules. Modules can be used to organize your Flex code into separate files. These files are compiled into SWFs and then can be loaded into your main application SWF at runtime. This is my first attempt are using modules and I've posted an example application (right click on the example to view the source files).

[More]

Comments (Comment Moderation is enabled. Your comment will not appear until approved.)
"It appears that the browser must go back to the server to download the SWF (I thought perhaps all the module SWFs would be downloaded in the background after the application loads)."

That is correct: There will be a delay because the modules are not downloaded in teh background. They are only loaded when requested. The browser caches them, though, so if you unload a module and then load it again, there will be no delay due to downloading.
# Posted By Matthew Horn | 1/8/07 1:44 PM
Further explanation... You CAN preload modules by using the IModuleInfo's load() method in, say, an application's creationComplete event handler. This will load the module but not display it.

For example:
ModuleManager.getModule("BarChartModule.swf").load();

hth,
matt horn
flex docs
# Posted By Matthew Horn | 1/8/07 3:04 PM
More to the point, how are you supposed to get data into and out of a module? Along with "how the hell do we compile these things in Flex Builder", this seems to be the most asked question at the moment.

Much as I appreciate Adobes hard work I think I would have rather waited another week and had some *usable* documentation. We know you're busy guys but so are we - my job is to build apps to deadline for clients, not to spend hours (along with hundreds of other people) second-guessing how changes to the tools work!
# Posted By ark | 1/9/07 5:00 AM
Matthew - thanks for posting more information about how to preload modules.

Ark - I'll continue to research and experiment with modules. But right now I'm thinking of using modules only as completely self-contained entities. My main application will not be exchanging data with the modules. I envision using modules to help me organize my code, make it easier to maintian, and lessen the initial download when its appropriate. Using modules may not be correct in some cases.

Adobe has posted updated documentation (see my references) and will continue to post new examples in their Developer center and Quick Start center on http://www.adobe.com/flex. Also much smarter Flex developers than I will be posting about how to use modules and what we can do with them. Finally, hopefully, some really good Flex 2 books will come out with even better code examples and information.

Lastly, since I don't work for Adobe, you may want to submit a change request to their Live Docs (see reference 2 above) for more examples and clarification. I've submitted changes to Adobe's Live Docs in the past and was impressed by their quick response. Just click on the Comment button that is on the bottom of a Live Docs page.
# Posted By Bruce | 1/9/07 6:41 AM
Hi Bruce, you app works fine.

I a design an modular application and having the following problem:

I've built a module (called Modulo1.swf) that contains a DataGrid and a couple of controls.
Then I made another module (called Modulo2.swf) that also contains a DataGrid and an Accordion.
Then I made a project called VisorModulos (ModuleViewer), it only load and unload this modules.
The error occurs after loading and unloading twice a module. It fails with the first module and also with the second, here is the link:

http://www.managernet.com.ar/modulos/VisorModulos....

To reproduce the error you must load and unload at least twice any module. In case of the first module, after loading for the second time, try using the DataGrid.

Right click to view source.

Any idea?
# Posted By Fabián Brussa | 1/9/07 11:31 AM
It looks like to me there is some problem with the code for module2.swf. I do get an error when trying to load module 2. I don't get an errors when loading or unloading module 2 several times in a row.

The code for module2.swf was not included in the view source.
# Posted By Bruce | 1/9/07 12:51 PM
Bruce.. the code for module2.swf is veri simple, only componentes whitin Script code. Try this: loading or unloading module 1 several times and try use the DataGrid.

I too recive the error where use tabnavigator, accordion or others controls. The problem is where unload and load the module.

thanks Bruce
# Posted By Fabián Brussa | 1/9/07 1:15 PM
Hi Bruce..

Now Update the sample :

http://www.managernet.com.ar/modulos/VisorModulos....
# Posted By Fabián Brussa | 1/9/07 2:34 PM
What are the best practices to debug modules?
I have tried to do it.. but debugger "freezes" when the module is being loaded...
(am i doing something wrong?)
# Posted By Juan Carlos M | 1/9/07 8:48 PM
Hi,

have you ever tried to load a module by using the moduleLoader as instance in a Actionscript (e.g. modLoader:ModuleLoader = new ModuleLoader()). I did that and I received no runtime-error but as a result the module to be loaded becomes never visible although I get the ready event from the loader.

Any ideas?

Regards Juergen
# Posted By Juergen Werle | 1/10/07 2:23 AM
Hi folks,

just found my mistake. I forgot to add the modLoader as a child of my application.

Sorry for this!

Juergen
# Posted By Juergen Werle | 1/10/07 2:37 AM
Juan:

I'm not sure what the "best practices" are for debugging modules. I've not done that myself. You may want to post your question on the FlexCoders Yahoo group (see my reference 4 above).

Fabian: I'm not able to determine what the problem is in your code.
# Posted By Bruce | 1/10/07 9:40 AM
Peter Ent posted an excellent example and tutorial with a code download on how to use Flex modules and how to communicate with modules.

See: http://weblogs.macromedia.com/pent/archives/2007/0...
# Posted By Bruce Phillips | 1/12/07 8:04 PM
Nice tips in http://weblogs.macromedia.com/pent/archives/2007/0...
;)
implements... that is a good one..
# Posted By Juan Carlos M | 1/13/07 6:30 AM
Hanks for this, it helped me get started. I also wrote up how to debug modules easily here: http://blog.kevinhammer.net/2007/01/debugging-with...
# Posted By Kevin Hammer | 1/16/07 12:40 AM
Hey, there's a new modules chapter here: http://blogs.adobe.com/flexdoc/
# Posted By Matthew Horn | 1/16/07 9:11 AM
I have a similar (or equal :P) trick to do the same as Kevin Hammer's <a href="http://blog.kevinhammer.net/2007/01/debugging-with... ">Debugging with Flex Modules</a>

my version is <a href="http://flex2colombia.wordpress.com/2007/01/11/debu...;
# Posted By Juan Carlos M | 1/16/07 5:24 PM
hi
very nice works..
thanks
# Posted By lazer epilasyon | 3/12/07 5:52 AM
Thanks this post
# Posted By Matbaa | 3/21/07 11:34 AM
I too recive the error where use tabnavigator, accordion or others controls. The problem is where unload and load the module.
# Posted By Dekorasyon | 3/21/07 11:35 AM
Thanks.. this post
# Posted By Estetik | 3/21/07 11:36 AM
Very goog comments. thanks
# Posted By Lazer Epilasyon | 3/21/07 11:36 AM
I'm not sure what the "best practices" are for debugging modules. I've not done that myself. You may want to post your question on the FlexCoders Yahoo group (see my reference 4 above).
# Posted By Estetik | 5/18/07 7:57 PM
You CAN preload modules by using the IModuleInfo's load() method in, say, an application's creationComplete event handler. This will load the module but not display it.

See: http://weblogs.macromedia.com/pent/archives/2007/0......
# Posted By estetik | 5/18/07 8:01 PM
Thank you..
# Posted By zonenoktaog ödüllü seo yar??mas? | 5/21/07 9:51 AM
Hi Bruce,

I tried to work out the sample in my Flex Builder. But my Flex builder doesn't recognizes mx:Module as well as mx:ModuleLoader command. What could be the problem.

I am using Flex builder 2.01
# Posted By ashwath | 5/28/07 9:43 PM
ashwath, sounds like you need to upgrade to 2.0.1. This is new functionality in that release.
# Posted By Matthew Horn | 5/29/07 6:35 AM
Ashwath - As Matthew states above. Check your Flex Builder version. A new version was released in January 2007. In Flex Builder click on HELP - ABOUT Adobe FlexBuilder 2. Version must be 2.0.1. This blog entries title is screwed up (2.01). Which to make it even more confusing, 2.01 was a previous version before 2.0.1 release.

See: http://www.adobe.com/support/flex/ for the 2.0.1 download.

I've never understood why Adobe released a new version of Flex and Flex Builder but named the version 2.0.1 instead of something like 2.5.
# Posted By Bruce | 5/29/07 10:42 AM
very nice module.Thank you
# Posted By tuzcuo?lu | 6/5/07 6:32 AM
sounds like you need to upgrade to 2.0.1. Thanks.
# Posted By galatasaray resimleri | 6/5/07 6:33 AM
This is nice.Congratulations and thank you.
# Posted By arama motoru optimizasyonu | 6/5/07 6:34 AM
Thank you bruce.
# Posted By endustri muhendisi | 6/5/07 6:41 AM
This is good.Thanx
# Posted By tuzcuoglu nakliye | 6/7/07 2:43 PM
thanks sir, its been very usefull for me but i am also searching for <mx:Module> application
# Posted By shashank | 6/19/07 11:17 PM
Nice module.Thank you
# Posted By iddaa tahminleri | 6/23/07 1:34 PM
thank you very much
# Posted By Mehmet Poyraz | 7/1/07 7:42 AM
hi
very nice works..
thanks
# Posted By ceviri | 7/1/07 3:04 PM
I've never understood why Adobe released a new version of Flex and Flex Builder but named the version 2.0.1 instead of something like 2.5.
# Posted By Alex | 7/6/07 11:10 AM
Hi,

I got a problem and need some help!

I init my mainApp with flashVars in the wrapper. Then I load a module in tha mainApp and want the module to get access the flashVars-String. I don't know how?
In other words, how can I get access to the functions or variables of the main-application within a module? Because, tryin the application.application.parameters failed, because its a module with the tag: mx:module !

Thanks, Steven
# Posted By Steven | 7/9/07 5:53 PM
I'm not exactly sure how you would do this is a module, but I assume it is similar to how you would do it in the main flex applicaiton.

Research the ActionScript 3.0 ExternalInterface class. It allows your Flex app to communicate with the JavaScript that is in the outer HTML wrapper.

See this tutorial on dmxzone.com:

http://www.dmxzone.com/ShowDetail.asp?NewsId=13688...

That tutorial helped me learn how to use the ExternalInterface class. It does cost $2.99 so you may also want to first review the ExternalInterface class information found in chapter 34, communicating with the wrapper, in the Flex Developer's Guide (see flex.org for a link to the developers guide).
# Posted By Bruce | 7/9/07 6:31 PM
Hi Bruce,

thank you for your quick answer! I will look at this tutor shortly!

I found out, that it is very easy - it's normally so ;-)

When a User loads my Page, my mainApp will be loaded from an wrapper with flashVars and then init. So now I can access the flashVars in my Application with - for example: variable = Application.application.parameters.sampleParameter !
That's in my Application.

So now, if I use a module and want to access the flashVar from that, I can use the following code in my module - for example: variable = parentApplication.parameters.sampleParameter !

And that's all for this little problem.

I use this for an relative path to the Host. My PHP save the HostURL as an FlashVar in the wrapper and call the mainApp. Now the mainApp and any Modules in there know where to call the other PHP-files with an HTTPService and request dbData which return as XML. I setup my hole application in one settings.php in which the HostURL is defined. So now if this changes, I don't need to recompile my App and Modules.

Thanks for answer and maybe my response could help another one with the same problem ;-)

Steven
# Posted By Steven | 7/9/07 7:25 PM
hi, guys Please do help me by sending some examples of Image Croping In Flex,
Its very Urgent As My Next Projects Most Important need is to Crop the images.

Please....Please....Please....Please.... Help Me Out.....
# Posted By shashank | 7/10/07 9:24 AM
Hi,

I got a problem and need some help!

I init my mainApp with flashVars in the wrapper. Then I load a module in tha mainApp and want the module to get access the flashVars-String. I don't know how?
In other words, how can I get access to the functions or variables of the main-application within a module? Because, tryin the application.application.parameters failed, because its a module with the tag: mx:module !

Thanks, Steven
# Posted By oda kap?s? | 8/4/07 1:08 AM
Oda - See the comment posted by Steven (just a few comments above yours) for a possible solution.
# Posted By Bruce | 8/5/07 11:42 AM
thanks
# Posted By kale kapi | 8/6/07 12:57 AM
Very good articles! Thank you!
# Posted By almanya vizesi | 8/8/07 3:45 AM
I init my mainApp with flashVars in the wrapper. Then I load a module in tha mainApp and want the module to get access the flashVars-String. I don't know how?
# Posted By kap? | 8/16/07 6:40 PM
Modules are loaded with a URL; you can pass parameters on this URL and then parse those parameters in the module. This is covered in the latest version fo the documentation, which you can download here:

http://blogs.adobe.com/flexdoc/modules/

hth,
matt horn
flex docs
# Posted By Matthew Horn | 8/17/07 6:10 AM
See the comment posted by Steven (just a few comments above yours) for a possible solution.
# Posted By download | 8/17/07 11:21 AM
Hi, nice web - site, and thanks a lot for all the useful informations, kind greetings from germany
# Posted By Zauberer Zauberkünstler Zaubershow | 8/18/07 3:26 AM
I init my mainApp with flashVars in the wrapper.
# Posted By dekorasyon | 8/19/07 5:52 AM
Hey;

Nice posts. Thank you.
# Posted By estetik | 8/20/07 1:47 PM
you can pass parameters on this URL and then parse those parameters in the module. This is covered in the latest version fo the documentation, which you can download here:
# Posted By kale kasa | 8/30/07 6:57 PM
Hi there, I found great ideas on your Web site, thanks for that and keep on doing
# Posted By Geburtstag zauberer | 9/5/07 11:21 PM
Hi, nice web - site, and thanks a lot for all the useful informations, kind greetings from germany
# Posted By Sportlernahrung | 9/7/07 2:32 AM
You should care of application.applicaion states
# Posted By kartvizit | 9/11/07 7:07 AM
you can pass parameters on this URL and then parse those parameters in the module.
# Posted By door | 9/12/07 6:43 PM
nice blogcontent . like it. illcome back
# Posted By ranking hosting | 9/13/07 9:35 PM
Thanks for the informative article and the time spent on it. I like your art and style of writing - it's good and interesting to read. Keep on such a good work - I'd like to reak more of your articles!
# Posted By toner | 9/15/07 1:42 AM
I use this for an relative path to the Host. My PHP save the HostURL as an FlashVar in the wrapper and call the mainApp. Now the mainApp and any Modules in there know where to call the other PHP-files with an HTTPService and request dbData which return as XML.
# Posted By games | 11/5/07 5:40 PM
I init my mainApp with flashVars in the wrapper. Then I load a module in tha mainApp and want the module to get access the flashVars-String. I don't know how?
# Posted By küvet | 11/7/07 7:57 AM
I init my mainApp with flashVars in the wrapper. Then I load a module in tha mainApp and want the module to get access the flashVars-String. I don't know how?
In other words, how can I get access to the functions or variables of the main-application within a module?
# Posted By kale kap? | 11/28/07 2:48 PM
you can pass parameters on this URL and then parse those parameters in the module.
# Posted By kale kapi | 11/28/07 2:49 PM
tHi folks,

just found my mistake. I forgot to add the modLoader as a child of my application.

Sorry for this!
# Posted By r10 | 12/8/07 9:58 AM
Hi,

PDF about Modular Application is great start point for learners.
# Posted By matbaa | 12/11/07 5:23 AM
Then I load a module in tha mainApp and want the module to get access the flashVars-String.
# Posted By stop smoking | 12/29/07 8:19 AM
Now I need to preload these modules along with application. Is this possible?
# Posted By kale yetkili servis | 1/21/08 3:44 AM
If you're inside a deeply nested component somewhere in a module, is there a simple way to get a reference to the containing module, similar to Application.application?

All I can think of is to keep passing that reference down to each subsequent child, but that seems a bit kludgy.
# Posted By GBFC | 1/23/08 2:54 PM
hi.
sory
I've never understood why Adobe released a new version of Flex and Flex Builder but named the version 2.0.1 instead of something like 2.5.
http://www.aydincelikkapi.com
# Posted By erdal | 1/24/08 1:37 AM
Now I need to preload these modules along with application. Is this possible? :(
# Posted By laminat parke | 2/10/08 7:22 AM
To create a module in ActionScript, you create a file that extends the mx.modules.ModuleBase class. Flex Builder 2.0.1 is the the best release of Flex ever. I'm working with flex builder 2.01 and they have put quite a bit of work into mx.modules. There weren't any examples anywhere, so I was left to explore the API documentation. Most of my day was spent wrestling in IIS PHP MYSQL hell getting a wiki setup, but after I got that done, I devoted fulltime to replacing my old classloader flex hacks with mx.modules.
# Posted By plastik | 3/1/08 12:40 AM
# Posted By Veronica | 3/28/08 5:16 AM
All I can think of is to keep passing that reference down to each subsequent child, but that seems a bit kludgy.
# Posted By prefabrik yapilar | 4/4/08 2:02 PM
Hi, i have a doubt, i am creating an application, in which i have 2 pages, one is list and second is detail, i just want to know that what i should to so that on clicking the button on detail page, i can get back to the list page. just simple linking in flex.
# Posted By Nishant | 5/23/08 12:10 AM
thx for the great stuff. Keep up your nice work
# Posted By Patterman | 6/3/08 1:06 AM
To create a module in ActionScript, you create a file that extends the mx.modules.ModuleBase class.
# Posted By hekimboard | 7/19/08 3:37 AM
TypeError: Error #1009: Cannot access a property or method of a null object reference.
   at ModuleInfo/completeHandler()[E:\dev\3.0.x\frameworks\projects\framework\src\mx\modules\ModuleManager.as:671]

I am getting this error. I cannot understand why. I have a very simple module with just a panel.
This is my module -pieModule.mxml
<?xml version="1.0" encoding="utf-8"?>
<mx:Module xmlns:mx="http://www.adobe.com/2006/mxml"; creationComplete="initPieModule()" layout="absolute" width="400" height="300">
<mx:Script><![CDATA[
import mx.controls.Alert;

   public function initPieModule():void {
      Alert.show("In Pie Module");
   }
   
]]></mx:Script>

<mx:Panel title="Pie Chart" height="100%" x="390" y="0" id="PnlPieChart" paddingBottom="10" paddingLeft="10" paddingRight="10">

</mx:Panel>
      
</mx:Module>

And this where I am calling it from
<?xml version="1.0" encoding="utf-8"?>
<mx:Canvas xmlns:mx="http://www.adobe.com/2006/mxml"; backgroundColor="green" height="100%" width="100%">
<mx:RemoteObject showBusyCursor="true" id="NGGraphRequest"
destination="ColdFusion"
source="FlexProjects.NGData">
<mx:method name="getNGGraphList" result="returnGraphHandler(event)" fault="mx.controls.Alert.show(event.fault.faultString)"/>
</mx:RemoteObject>


<mx:Script>
<![CDATA[
   import mx.events.ListEvent;
   import mx.events.FlexEvent;
   import mx.rpc.events.ResultEvent;
    import mx.rpc.events.FaultEvent;
    import flash.events.Event;
    import mx.collections.ArrayCollection;
    import mx.utils.ArrayUtil;
    import mx.controls.Alert;
    import mx.binding.utils.*;
import mx.utils.ObjectUtil;
import mx.charts.ChartItem;
import mx.charts.HitData;
import mx.charts.chartClasses.IAxis;
import mx.charts.chartClasses.Series;
import mx.charts.series.ColumnSet;
import mx.charts.series.items.ColumnSeriesItem;
import mx.utils.StringUtil;

import mx.modules.*;
import mx.events.ModuleEvent;
import mx.managers.SystemManager;
public var lcModule:IModuleInfo;
public var lcm:Object;
public var firsttime:Boolean;

   [Bindable]
private var graphData:ArrayCollection;

public var headerid:int;
private var gindex:int;

[Bindable]
public var dpGraph:ArrayCollection;

[Bindable]
public var dpRowData:Object;
//public var dpRowData:Object;

   public function initGraph():void
   {
      
      NGGraphRequest.getNGGraphList(headerid);
   }

   private function returnGraphHandler(e:ResultEvent):void
   {
      graphData = e.result as ArrayCollection;
      //Alert.show("array length is " + graphData.length);
      for (gindex=0;gindex<=graphData.length-1; gindex++) {
         //Alert.show("Graphtype is " + graphData[i].GRAPHTYPE);
         switch(graphData[gindex].GRAPHTYPE) {
            case "LINE GRAPH":
            case "STACKED LINE CHART":
       //lcModule = ModuleManager.getModule("LineChartModule.swf");
       //lcModule.addEventListener("ready", getLCModuleInstance);
       //lcModule.load();   
       //if (firsttime == true) {
          var m1:ModuleLoader = new ModuleLoader();
          var gid:int = graphData[gindex].GRAPHID;
          m1.url = "LineChartModule.swf";
          m1.addEventListener(ModuleEvent.READY, function (e:ModuleEvent) : void {
          LCListener(e,gid,gindex,m1); });
       m1.addEventListener(ModuleEvent.ERROR, LCListenerErr);
                  m1.loadModule();
                  this.addChildAt(m1,gindex);
               //this.addChild(m1);
       //}
               break;
            case "COLUMN CHART":
       var m2:ModuleLoader = new ModuleLoader();
       var gid_cc:int = graphData[gindex].GRAPHID;
       m2.url = "ColChartModule.swf";
       m2.addEventListener(ModuleEvent.READY, function (e:ModuleEvent) : void {
      CCListener(e,gid_cc,gindex,m2); });
   m2.addEventListener(ModuleEvent.ERROR, CCListenerErr);
               m2.loadModule();
               this.addChildAt(m2,gindex);
               break;
            case "PIE CHART":
               var mPie:ModuleLoader = new ModuleLoader();
               mPie.url = "PieModule.swf";
               mPie.addEventListener(ModuleEvent.READY,pieListener);
               //mPie.loadModule();
               this.addChild(mPie);
               /*
       var m3:ModuleLoader = new ModuleLoader();
       var gid_pie:int = graphData[gindex].GRAPHID;
       Alert.show("graphid - pie is " + gid_pie);
       Alert.show("In Graph Component " + ObjectUtil.toString(dpRowData));
      
       m3.url = "PieChartModule.swf";
      
       m3.addEventListener(ModuleEvent.READY, function (e:ModuleEvent) : void {
      PieListener(e,gid_pie,gindex,m3); });
   m3.addEventListener(ModuleEvent.ERROR, PieListenerErr);
   
               m3.loadModule();
               this.addChild(m3);
               */
               break;
            case "STACKED COLUMN CHART":
               break;
         }
      }
   }

   public function LCListenerErr(e:ModuleEvent):void {
      Alert.show("Errror in Line Chart Module");
   }

   public function CCListenerErr(e:ModuleEvent):void {
      Alert.show("Errror in Column Chart Module");
   }

   public function PieListenerErr(e:ModuleEvent):void {
      Alert.show("Errror in PieChart Module" + e.errorText);
   }

   public function pieListener(e:ModuleEvent):void{
      Alert.show("Pie chart module is ready");
   }
/*
   public function PieListener(e:ModuleEvent,graphid:int,graphinx:int,m3:ModuleLoader):void {
      //Alert.show("In Graph Component " + ObjectUtil.toString(dpRowData));
      var ichild3:* = m3.child as IPieChart;
      if(ichild3 != null) {
         ichild3.setpieDataProvider(dpRowData);
         ichild3.setpieGraphid(graphid);
         ichild3.setpieGraphinx(graphinx);
      }    
      //Alert.show("In ready event listener");
   }
*/

   public function LCListener(e:ModuleEvent,graphid:int,graphinx:int,m1:ModuleLoader):void {
      var ichild:* = m1.child as ILineChart;
      if(ichild != null) {
         ichild.setlcDataProvider(dpGraph);
         ichild.setlcGraphid(graphid);
         ichild.setlcGraphinx(graphinx);
      }    
      //Alert.show("In ready event listener");
   }

   public function CCListener(e:ModuleEvent,graphid:int,graphinx:int,m2:ModuleLoader):void {
      //Alert.show("In Grph Componenet " + ObjectUtil.toString(dpRowData));
      var ichild:* = m2.child as IColChart;
      if(ichild != null) {
         ichild.setccDataProvider(dpRowData);
         ichild.setccGraphid(graphid);
         ichild.setccGraphinx(graphinx);
      }    
      //Alert.show("In ready event listener");
   }
   

]]>
</mx:Script>
   
</mx:Canvas>

Please let me know why I get this error. And another point to note - this error is sporadic. Sometimes it goes through and sometimes it doesn't.

Thanks
# Posted By Ambika Dayal | 9/5/08 5:55 AM
Hi, i have a doubt, i am creating an application, in which i have 2 pages, one is list and second is detail, i just want to know that what i should to so that on clicking the button on detail page, i can get back to the list page. just simple linking in flex.
# Posted By izlekop | 10/19/08 2:40 AM
BlogCFC was created by Raymond Camden. This blog is running version 5.9.1.002. Contact Blog Owner