---
title: "[Flex] two ways of loading modules"
author: "SilverRing"
date: "2010-10-14T22:42:02Z"
tags: []
categories: ["Web前端"]
slug: "flex-two-ways-of-loading-modules"
draft: false
lastmod: "2010-10-14T22:42:35Z"
id: 785287
url: "https://silverring.iteye.com/blog/785287"
---

There're two ways of loading and unloading modules:

ModuleLoader - higher level API
ModuleManager - lower level API

1. Using ModuleLoader

1) define a ModuleLoader


```xml

<mx:ModuleLoader id="moduleLoader"/>

```


2) when the button of loading the module is clicked


```java

moduleLoader.url = "SimpleModule.swf";
moduleLoader.loadModule();

```


3) add module load ready listener


```java

moduleLoader.addEventListener( ModuleEvent.READY, moduleReadyHandler);

```


4) define the listener method


```java

private function moduleReadyHandler( event: ModuleEvent ): void {
    trace("SimpleModule is loaded");
}

```


5) to unload a module


```java

moduleLoader.unloadModule();

```



2. Using ModuleManager 

1) load the module and specify the ready event listener


```java

info = ModuleManager.getModule("SimpleModule.swf");
info.addEventListener(ModuleEvent.READY, moduleReadyHandler);
info.load();

```


2) unload the module by using the same info object


```java

info.addEventListener(ModuleEvent.UNLOAD, moduleUnloadHandler);
info.unload();

```



No matter what method is used, we need to make sure when the loaded Module is safe for communication. Here is how to do it: by add a creationComplete listener in moduleReadyHandler.


```java

moduleLoader.child.addEventListener(FlexEvent.CREATION_COMPLETE, 
      moduleCreationCompleteHandler);

```


inside moduleCreationCompleteHandler:


```java

protected function moduleCreationCompleteHandler(event:FlexEvent):void
{
    moduleLoader.child.removeEventListener(FlexEvent.CREATION_COMPLETE,
      moduleCreationCompleteHandler);

   // further processings...
}

```



Someone might encounter the memory leak issue when trying to unload a module. This is a nice article to look into:

http://blogs.adobe.com/aharui/2009/08/what_we_know_about_unloading_m.html