»
S
I
D
E
B
A
R
«
Stylish modules and sub applications.
Feb 8th, 2010 by Gaurav

One of the features that’s coming with Flex 4 is “Per-Module Style Management”. There is a lot that can be written about this feature and it probably can’t be covered in a single post. So for starters here is a small introduction.

The feature for Per-Module Style Management was done to allow modules and sub applications to be able to manage their own styles. With this feature StyleManager will no longer be a singleton and as a result that will allow modules and sub applications to have their own instances of StyleManager.

Modules and sub applications will continue to inherit styles from the parent application/module. But only the style properties not defined by the child modules or sub applications will trickle down (i.e. child module/application will be able to override a style property defined by the parent). There will also be merging of styles properties.

To understand this better, lets take a look at a sample. Following is the code for a parent application:

<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 
			   xmlns:s="library://ns.adobe.com/flex/spark" 
			   xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="1024" minHeight="768" creationComplete="application1_creationCompleteHandler(event)">
	<fx:Style>
		@namespace s "library://ns.adobe.com/flex/spark";
		@namespace mx "library://ns.adobe.com/flex/mx";
 
		global {
			chromeColor: #DDAA66;	
		}
 
		s|DropDownList
		{
			fontStyle: italic;
		}
 
		s|Button#gumboButton
		{
			fontStyle: italic;
		}
 
		s|Panel s|Label
		{
			fontStyle: italic;
		}
 
		s|Button.myStyle
		{
			fontStyle: italic;
		}
 
		s|HGroup s|RichText
		{
			fontStyle: italic;
		}
 
		.classOfStyle
		{
			fontStyle: italic;
		}
 
	</fx:Style>
 
	<fx:Script>
		<![CDATA[
			import mx.events.FlexEvent;
			import mx.collections.ArrayList;
			import mx.events.ModuleEvent;
			import mx.events.StyleEvent;
			import mx.controls.Alert;
 
			private var arr:Array =
				[
					{ label:'Apple', data:10.00},
					{ label:'Banana', data:15.00 },
					{ label:'Melon', data:3.50 },
					{ label:'Kiwi', data:7.65},
					{ label:'Strawberry',data:12.35 },
					{ label:'Other', data:00.00}
				];
 
			private var listArr :ArrayList = new ArrayList(arr);
 
			protected function application1_creationCompleteHandler(event:FlexEvent):void
			{
				appList.dataProvider = listArr;
			}
 
			public function load():void
			{
				if(mod_loader.url == null)
				{
					mod_loader.url = "LoadStylesModule.swf";	
				}
				else
				{
					mod_loader.loadModule();
				}
 
			}
 
			public function unload():void
			{
				mod_loader.unloadModule();
			}
 
		]]>
	</fx:Script>
	<s:layout>
		<s:VerticalLayout />
	</s:layout>
	<s:HGroup>
		<s:VGroup id="groupId">
			<s:VGroup >
				<s:CheckBox id="checkBox" label="Check Box" />
				<s:Label text="Label Outside Panel"  />
			</s:VGroup>
			<s:HGroup rotation="10">
				<s:NumericStepper id="numericStepper" stepSize="1" minimum="1" maximum="10" />
				<s:RichText text="This Text is Rich !!" />
			</s:HGroup>
			<s:RichText text="This Text is also Rich !!" />
			<s:Panel title="Gumbo Panel" id="appPanel" rotation="-5">
				<s:layout>
					<s:VerticalLayout />
				</s:layout>
				<s:Button id="gumboButton" label="Gumbo Button"  />
				<s:Button id="gumboButton2" label="Second Gumbo Button" styleName="myStyle"  />
				<s:Label text="Spark Label"  />
				<s:Label text="Spark Label class selector" styleName="classOfStyle"  />
				<s:DropDownList id="appList"  />
			</s:Panel>
		</s:VGroup>	
		<mx:ModuleLoader id="mod_loader"/>
	</s:HGroup>
 
	<s:Button label="Load Module" click="load()" />
	<s:Button label="Unload Module" click="unload()" />
</s:Application>

If you notice, the above code defines a bunch of styles. It sets the chrome color to DDAA66 in the global selector and it sets the fontStyle to italic using various selectors (class, Id, Type, descendant).

Now let’s take a look at the code of the module (LoadStylesModule.mxml):

<?xml version="1.0" encoding="utf-8"?>
<mx:Module xmlns:fx="http://ns.adobe.com/mxml/2009" 
		   xmlns:s="library://ns.adobe.com/flex/spark" 
		   xmlns:mx="library://ns.adobe.com/flex/mx" creationComplete="module1_creationCompleteHandler(event)">
	<fx:Script>
		<![CDATA[
			import mx.collections.ArrayList;
			import mx.controls.Alert;
			import mx.events.FlexEvent;
			import mx.events.StyleEvent;
 
			private var arr:Array =
				[
					{ label:'Apple', data:10.00},
					{ label:'Banana', data:15.00 },
					{ label:'Melon', data:3.50 },
					{ label:'Kiwi', data:7.65},
					{ label:'Strawberry',data:12.35 },
					{ label:'Other', data:00.00}
				];
 
			private var listArr :ArrayList = new ArrayList(arr);
 
			protected function module1_creationCompleteHandler(event:FlexEvent):void
			{
				moduleList.dataProvider = listArr;
				localStyleManager  = StyleManager.getStyleManager(this.moduleFactory);
			}
 
			private var localStyleManager:IStyleManager2 = null;
 
			public var eventDispatcher:IEventDispatcher = null;
			protected function loadStylesButton_clickHandler(event:MouseEvent):void
			{
 
				eventDispatcher = localStyleManager.loadStyleDeclarations("testStyles.swf");
			}
 
			protected function unloadStylesButton_clickHandler(event:MouseEvent):void
			{
				localStyleManager.unloadStyleDeclarations("testStyles.swf");
			}
		]]>
	</fx:Script>
	<s:VGroup>
		<s:CheckBox id="checkBox" label="Check Box Module" />
		<s:Label text="Label Outside Panel"  />
		<s:HGroup rotation="-10">
			<s:NumericStepper id="numericStepper" stepSize="1" minimum="1" maximum="10" />
			<s:RichText text="This Text is Rich Module !!" />
		</s:HGroup>
		<s:RichText text="This Text is also Rich !!" />
		<s:Panel title="Gumbo Module Panel" id="appPanel" rotation="-5">
			<s:layout>
				<s:VerticalLayout />
			</s:layout>
 
			<s:Button id="gumboButton" label="Gumbo Module Button"  />
			<s:Button id="gumboButton2" label="Second Gumbo Module Button" styleName="myStyle"  />
			<s:Label text="Spark Module Label"  />
			<s:Label text="Spark Label Module class selector" styleName="classOfStyle"  />
			<s:ComboBox id="moduleList" height="24" width="147" />
		</s:Panel>
	</s:VGroup>	
	<mx:Button label="Load styles" id="loadStylesButton" click="loadStylesButton_clickHandler(event)" />
	<mx:Button label="Unload styles" id="unloadStylesButton" click="unloadStylesButton_clickHandler(event)" />
</mx:Module>

The code for the module above does not define any styles. So what that means is that it will inherit the styles from the parent app. It will have the chrome color of DDAA66 for all components and also the font styles will be italic. So far that’s all normal and boring stuff. Now you probably also noticed that the module loads a styles declaration swf (which is a css compiled to a swf), and when you load the styles swf you will see the magic of per-module style management. The module will override style definition for some properties (originally defined in the main app) and for other properties styles merging will happen.

Here is the code for the css (testStyles.css):

@namespace s "library://ns.adobe.com/flex/spark";
@namespace mx "library://ns.adobe.com/flex/mx";
 
s|DropDownList
{
	borderColor: #FF0000;
	fontSize: 16;
}
 
s|Button#gumboButton
{
	chromeColor: #AAFFAA;
	fontSize: 16;
}
 
s|Panel s|Label
{
	fontSize: 16;
}
 
s|Button.myStyle
{
	chromeColor: #FFFFAA;
	fontSize: 14;
}
 
s|HGroup s|RichText
{
	chromeColor: #BBAAAA;
	fontSize: 14;
}
 
.classOfStyle
{
	color: #0FFFFA;	
	fontSize: 20;
}

Here is the running swf:



Click on the “Load Module” button to load the module. Once the module is loaded, notice the chrome color of most components is the same as in the parent app and the font is italicized for most components – this shows that the module inherits styles from the parent app. Now click on the “Load styles” button in the module, once the styles swf is loaded you can notice that the font size changes for most components but the fonts in the module are still italicized – this shows styles merging because we were only overriding the fontSize in the css and not the fontStyle property. Also notice the new chrome color for components in the module, its now different from the global chrome color (DDAA66). So the module is able to override the styles properties it chooses.

So, hopefully you find this short introduction useful. Stay tuned for more on this.. And if you want me to write about something else, please say so with your comments (which btw are welcome ;-) )

Creating smaller swfs (Part III)
Jul 16th, 2009 by Gaurav

Here is the part three..

The very fact that you are writing applications using Flex proves that you care about user interface. And one of the features of Flex that enables you to provide a better user experience is font embedding. There are many benefits of using embedded fonts but the most important one is that it provides consistency regarding how the application will appear across different client environments and you don’t need to make sure whether the font is pre-installed. But there can also be few disadvantages of using embedded fonts, like when you use embedded font it gets stitched into your SWF which results in increasing the overall size of the SWF.

So lets look at how you can reap the benefits of using embedded fonts while still avoiding the start up time cost due to a larger SWF. The trick for doing this is to use Modules (for embedding fonts) and avoid embedding the fonts in the main SWF. That way you can achieve smaller start up time and fetch the fonts when you need to use them.

Here is an example of an application that displays text using four different fonts:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" 
		layout="vertical" width="650" height="400"
		verticalAlign="middle" horizontalAlign="center" 
		creationComplete="creationCompleteHandler(event)">
	<mx:Script>
		<![CDATA[
			import mx.events.ModuleEvent;
			import mx.modules.ModuleManager;
			import mx.modules.IModuleInfo;
			import mx.events.FlexEvent;
			import mx.controls.Alert;
			import mx.validators.Validator;
			private var fontModuleInfo:IModuleInfo;
 
			protected function button_clickHandler(event:MouseEvent):void {
				if(currentState != 'LoggedIn') {
					var validators:Array = [];
					validators[0] = this.v0;
					validators[1] = this.v1;
 
					var inValid:Array = Validator.validateAll(validators);
					if(inValid.length ==0) {
						if(tiUserName.text == 'guest' 
							&& tiPassword.text =='guest') {
							currentState = 'LoggedIn';
						} else {
							Alert.show("Invalid username" +
								" or password."); 
						}
					}
				} else {
					currentState = '';
				}
			}
 
			protected function creationCompleteHandler(event:FlexEvent):void 
			{
				fontModuleInfo = ModuleManager.getModule("FontModule.swf");
				fontModuleInfo.addEventListener(ModuleEvent.READY,
					readyHandler);
				fontModuleInfo.load();
			}
 
			private function readyHandler(event:Event):void {
				fontModuleInfo.factory.create();
			}
 
		]]>
	</mx:Script>
 
	<mx:StringValidator source="{tiUserName}" property="text" id="v0"
						required="true" maxLength="10" 
						trigger="{loginButton}" triggerEvent="click" />
	<mx:StringValidator source="{tiPassword}" property="text" id="v1"
						required="true" maxLength="10" 
						trigger="{loginButton}" triggerEvent="click" />
 
	<mx:states>
		<mx:State name="LoggedIn">
			<mx:RemoveChild target="{loginPanel}"/>
			<mx:AddChild relativeTo="{loginButton}" position="before">
				<mx:Panel id="pnl" title="Labels with different fonts. 
						  Embedded fonts can be rotated." paddingTop="10" 
						  paddingBottom="10" paddingLeft="10" paddingRight="10">
					<mx:Label id="lblVerdana" 
						  styleName="myVerdanaDescriptor" rotation="1"  
						  text="The quick brown fox jumps over the lazy dog." />
					<mx:Label id="lblCandara" 
						  styleName="myCandaraDescriptor" rotation="1"
						  text="The quick brown fox jumps over the lazy dog." />
					<mx:Label id="lblVrinda" 
						  styleName="myVrindaDescriptor" rotation="1"
						  text="The quick brown fox jumps over the lazy dog." />
					<mx:Label id="lblMinion" 
						  styleName="myMinionDescriptor" rotation="1"
						  text="The quick brown fox jumps over the lazy dog." />
				</mx:Panel>
			</mx:AddChild>
			<mx:SetProperty target="{loginButton}" 
							name="label" value="Log Out"/>
		</mx:State>
	</mx:states>
 
	<mx:Panel id="loginPanel" 
			  title="Login"  borderAlpha="0.15"
			  horizontalScrollPolicy="off" verticalScrollPolicy="off">
 
		<mx:Form id="loginForm" >
			<mx:FormItem label="Username:">
				<mx:TextInput id="tiUserName" />
			</mx:FormItem>
			<mx:FormItem label="Password:">
				<mx:TextInput id="tiPassword" 
							  displayAsPassword="true" />
			</mx:FormItem>
		</mx:Form>
	</mx:Panel>
	<mx:Button label="Login" id="loginButton" 
			   click="button_clickHandler(event)"/>
</mx:Application>

And here is the module (FontModule.mxml) used to embed fonts:

<?xml version="1.0" encoding="utf-8"?>
<mx:Module xmlns:mx="http://www.adobe.com/2006/mxml">
	<mx:Style>
		@font-face {
			src:url("verdana.TTF");
			fontFamily: myVerdana;
		}
 
		.myVerdanaDescriptor
		{
			fontFamily: myVerdana;
			color: red;
			fontSize: 24;
		}
 
		@font-face {
			src:url("MinionPro-Regular.otf");
			fontFamily: myMinion;
		}
 
		.myMinionDescriptor
		{
			fontFamily: myMinion;
			color: green;
			fontSize: 24;
		}
 
		@font-face {
			src:url("Vrinda.ttf");
			fontFamily: myVrinda;
		}
 
		.myVrindaDescriptor
		{
			fontFamily: myVrinda;
			color: red;
			fontSize: 24;
		}
 
		@font-face {
			src:url("CANDARA.TTF");
			fontFamily: myCandara;
		}
 
		.myCandaraDescriptor
		{
			fontFamily: myCandara;
			color: green;
			fontSize: 24;
		}
	</mx:Style>
</mx:Module>

Below is the running sample, to log in use “guest” as user name and password and click on the button.



The size benefits:

Configuration Swf size Comments
If fonts are embedded in main swf 607 KB  
If fonts are fonts embedded in module 267 KB The font Module is 354 KB
If fonts are fonts embedded in module and main app uses default SDK RSLs. (as is the case with the above example) 84 KB This app was compiled with Flex 4 beta build. With a more recent Flex 4 build there should be increased benefits for swf size reduction.

So we trimmed the SWF by 86% for this sample.

The above approach works if you don’t need embedded fonts right at the application start up. In the above example the font module is loaded after the main app is initialized, as we don’t need to show text using embedded fonts on the log in screen. This way the user experiences a reduced start up time and you can still use the fonts you like ;)

If you app uses multiple fonts and some of them are not required at the application start up, consider embedding fonts in a module.

Creating smaller swfs (Part II)
Jun 23rd, 2009 by Gaurav

Here is the “Part II” of creating smaller swfs. In case you haven’t checked out the “Part I”, it can be found here: Creating smaller swfs (Part I). In this post, let’s focus on modules and how they can help in reducing the swf size.

What are Modules?

Modules are Flex swf files that can be dynamically loaded by other swf files. So they allow you to break your large application into smaller pieces and gives you the flexibility to load the the required piece when/if required. In case you are wondering “How is Module different than RSL (since RSL can also be a swf and can be loaded by your application)”, the difference is that RSLs can only be loaded in frame 1 (i.e before your application initializes) but Modules can be loaded and unloaded whenever you want (after your application initializes) through out the life cycle of your application. Also note that you can not run modules independently, they always need to be loaded by another application. Benefits of modules are much more than just helping you to make your swf smaller, some of the benefits are:

  • Improve start up time by reducing the swf size.
  • Improves development time because modules allows for code separation and can be independently compiled. So you can break you app into different functional pieces and have different developers/teams work on the different pieces as Modules.
  • Improves build time because you need not recompile your entire application if changes are made to an independent module.
  • Improves integration where you can’t upgrade all your code to the most recent version of Flex.

How to write Modules?

You can write a module either using ActionScript or MXML. If your module is going to use any part of the Flex framework code then you must write a module based on mx.modules.Module. In case your module is not going to use any part of the Flex framework code then you can write a module based on mx.modules.ModuleBase but then you must write it using ActionScript.

Here is an example of a module written using MXML (DataGridModule.mxml):

<?xml version="1.0" encoding="utf-8"?>
<mx:Module xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical"
		   width="400" height="300" creationComplete="module1_creationCompleteHandler(event)">
	<mx:Script>
		<![CDATA[
			import mx.controls.Alert;
			import mx.rpc.events.FaultEvent;
			import mx.events.FlexEvent;

			protected function module1_creationCompleteHandler(event:FlexEvent):void
			{
				srv.send();
			}

			protected function srv_faultHandler(event:FaultEvent):void
			{
				Alert.show("Can not retrieve data");
			}
		]]>
	</mx:Script>

	<mx:HTTPService id="srv" url="catalog.xml" fault="srv_faultHandler(event)" />

	<mx:DataGrid dataProvider="{srv.lastResult.report.account}" width="100%" height="100%">
		<mx:columns>
			<mx:DataGridColumn dataField="month" headerText="Month"/>
			<mx:DataGridColumn dataField="sales" headerText="Sales" textAlign="right"/>
			<mx:DataGridColumn dataField="expenses" headerText="Expenses" textAlign="right"/>
		</mx:columns>
	</mx:DataGrid>
</mx:Module>

As you can see the only thing special about the above code is the wrapping <mx:Module> tag, otherwise it looks pretty similar to a custom component (You can simply replace <mx:Module>, with say <mx:VBox> or <mx:HBox> and use it as a custom component)

The following is an example of a Module using ActionScript (ActionModule.as) which extends mx.modules.ModuleBase:

package
{
	import mx.modules.ModuleBase;

	public class ActionModule extends ModuleBase
	{
		public function ActionModule()
		{
			super();
		}

		public function calculateAverageProfit(arr:Array): String
		{
			var profit:Number = 0;

			for(var counter:int = 0; counter < arr.length; counter++)
			{
				var obj:Object = arr[counter];
				profit += obj.sales - obj.expenses;
			}

			return new Number(profit/arr.length).toFixed(2);
		}
	}
}

Since the above module (ActionModule.as) is for calculation purpose only, it doesn't depend upon any framework code and hence can extend from mx.modules.ModuleBase instead of mx.modules.Module

How to use Modules?

So now you probably have some idea about writing the modules, once you write the Modules, there are two techniques to load them into your application.

  1. Use ModuleLoader
  2. Use ModuleManager and IModuleInfo

Following is an example of an app which loads Module(s) (using both the techniques):

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical"
creationComplete="srv.send();">
	<mx:Script>
		<![CDATA[
			import mx.modules.IModuleInfo;
			import mx.modules.ModuleManager;
			import mx.events.ModuleEvent;
			import mx.collections.ArrayCollection;
			import mx.rpc.events.ResultEvent;
			import mx.controls.Alert;
			import mx.rpc.events.FaultEvent;
			import mx.events.FlexEvent;

			private var result:ArrayCollection;

			private var moduleInfo:IModuleInfo;

			private var obj:Object;

			protected function srv_faultHandler(event:FaultEvent):void
			{
				Alert.show("Can not retrieve data");
			}
			protected function modLoader_errorHandler(event:ModuleEvent):void
			{
				Alert.show("Error in loading the Module.");
			}

			protected function srv_resultHandler(event:ResultEvent):void
			{
				result = event.result.report.account;
				linechart.dataProvider = result;
			}

			protected function showDataGrid_clickHandler(event:MouseEvent):void
			{
				modLoader.url = "DataGridModule.swf";
			}

			protected function showProfit_clickHandler(event:MouseEvent):void
			{
				moduleInfo = ModuleManager.getModule("ActionModule.swf");
				moduleInfo.addEventListener(ModuleEvent.READY, readyHandler);
				moduleInfo.addEventListener(ModuleEvent.ERROR, modLoader_errorHandler);
				moduleInfo.load();
			}

			private function readyHandler(event:ModuleEvent):void
			{
				obj = moduleInfo.factory.create();
				profitLbl.text = "Average Profit: $" + obj.calculateAverageProfit(result.source)
                                                 + " (in millions)";
			}
		]]>
	</mx:Script>
	<mx:HTTPService id="srv" url="catalog.xml" fault="srv_faultHandler(event)"
                         result="srv_resultHandler(event)"/>

	<mx:LineChart id="linechart" color="0x323232" height="50%" showDataTips="true" >
		<mx:horizontalAxis>
			<mx:CategoryAxis categoryField="month"/>
		</mx:horizontalAxis>
		<mx:series>
			<mx:LineSeries yField="sales" form="curve" displayName="Sales"/>
			<mx:LineSeries yField="expenses" form="curve" displayName="Expenses"/>
		</mx:series>
	</mx:LineChart>
	<mx:Legend dataProvider="{linechart}" color="0x323232"/>
	<mx:Label id="profitLbl" />
	<mx:Button id="showProfit" click="showProfit_clickHandler(event)"
                 label="Show Average Profit"/>
	<mx:Button id="showDataGrid" click="showDataGrid_clickHandler(event)"
                 label="Show Details"/>

	<mx:ModuleLoader id="modLoader" error="modLoader_errorHandler(event)" />
</mx:Application>

In the above example the DataGridModule.swf is loaded using <mx:ModuleManager/>, the load is invoked when the url property is set (modLoder.url ="DataGridModule.swf"), which fires the urlChange event. Also you can invoke the load operation using the loadModule() method of ModuleLoader. You can unload a module using the unloadModule() method.

The ActionModule.swf is loaded using ModuleManager and IModuleInfo, ModuleManager is used to get a reference to the IModuleInfo for ActionModule.swf and the actual load is invoked using the load() method on IModuleInfo.

Notice that both techniques allow you to add a error handler (see modLoader_errorHandler() which takes event of type ModuleEvent), a error handler can be helpful to debug issue with module loading. Also there are other event types that you can use to find info related to loading (ModuleEvent.PROGRESS, ModuleEvent.READY, ModuleEvent.SETUP)

Here is the running swf. When you press on the button to "Show Average Profit", it loads the ActionModule.swf (which calculates the average profit). When you press on "Show Details", it loads the data grid module which shows the data in a datagrid.



Now for the size benefits:

Configuration Swf size Comments
Without Modules and RSLs 484 KB  
With Modules 415 KB In this case the benefit is small because we moved only a small portion of code into the module. Reduction in swf size depends upon the amount of code you move into modules. Expect higher benefits for large applications.
With Modules and RSLs 159 KB This app was compiled with Flex 4 beta build. With a more recent Flex 4 build there should be increased benefits for swf size reduction.

Optimizing Modules

So far you have seen how to use modules and how they can help to reduce the swf size. But when you compile a module swf, lot of core classes of the Flex framework (which are dependencies of mx.modules.Module) also get stitched into the module swf file, this creates a situation where you duplicate the same classes into your application (once in the main app and then in each module which is loaded by the app). However there is a compiler option to avoid this situation. You can compile you main app with the -link-report option, it will give you the link-report (a report that has the information regarding the byte code linkage) for your application. Then you can compile your module(s) with the -load-externs option and you can point the load-externs to the generated link report from the compilation of the main app. Its like telling the compiler that you already have taken care of classes which are in the link report, so don't add those to the module swf file.

Here are the example command I used:

# compile main app - this will generate the main app swf and a link report named myLinkReport.xml
./mxmlc -link-report=myLinkReport.xml Dashboard.mxml

# compile module
./mxmlc -load-externs=myLinkReport.xml DataGridModule.mxml

Or you can also use Flex/Flash Builder to set up the module optimization. You can do this via the project properties. Here are the steps:

  1. Right Click on the project and go to properties
  2. Choose Flex Modules

  3. You can see the modules in this dialog and whether they are being optimized or not. You can add new modules using the "Add" button.

  4. Edit setting using the edit button or double click on the module

  5. Using this dialog, you can choose whether to optimize(and for which application) or not

The only situation where you should not optimize your modules is when you want to use your modules in different applications. Because optimized modules can only be used with application for which they were optimized.

Shared Code problem

When modules are loaded, the classes that are contained in the module are added into the child domain of the current application domain. So classes that are part of the module are owned by the module and not be the application. This can create an issue when two modules are using the same classes. When the first module has loaded, its class definitions gets registered, and module loaded after wards finds itself in a situation where the class definition that it contains doesn't matches with what is already registered. This usually creates issue with the manager classes like HistoryManager, PopUpManager etc. The error usually is a "Type Coercion" error, for example:

Type Coercion failed: cannot convert mx.managers::PopUpManagerImpl@ to mx.managers.IPopUpManager

The solution is to make these classes part of the main app (so the main app is the owner of these class definitions and both managers can share them). If you simply add the import and variable declaration to the script block of the main app, you can avoid the issue with the classes that cause shared code problem

import mx.managers.HistoryManager;
private var managerObj: HistoryManager;

Alternatively you can also refactor code into a shared module and load the shared module before loading any other module.

Modules and RSLs

Using both modules are RSLs can significantly reduce swf size and start-up time. But if your app is using RSL (say for framework.swc) then your module swf does not need to use framework.swc as RSL. In such cases the library that will be loaded as RSL by the main app should just be in the external-library-path of the module.

This way since the RSL will already be loaded by the main app and available for consumption, for the module, the module will further save on load time because it won't even try to load the RSL (btw since the RSL is already loaded by the main app, the module will get it quickly get it from the cache so the saving per module is small but can add up if you are using lots of modules)

There is a bug (see FB-15470) related to this in Flex Builder 3. The fix for the bug will be available in Flash Builder 4

So if you are using FB 3, here is how you can do this manually:
You should move the modules into a seperate Flex Builder project and not list the libraries as rsls (instead just as -external-library-path for the libraries). That way the modules won't try to reload the rsls (because they would have already been loaded by the main app (for the project containing the main app you can continue to have the libraries listed as rsls))

»  Substance: WordPress   »  Style: Ahren Ahimsa