Flex 4.6 中使用ActionScript 中载入模块的方法
- 模块代码
- <?xml version="1.0" encoding="utf-8"?>
- <s: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" width="400" height="300">
- <fx:Declarations>
- <!-- 将非可视元素(例如服务、值对象)放在此处 -->
- </fx:Declarations>
- <s:Button label="按钮">
- </s:Button>
- </s:Module>
有些文章说 不能 用
- s:Module
只能用
- mx:Module
否则有未明错误发生。
我测试下来,在 flash builder 4.6 的版本下,不会产生错误。
- 调用代码
- <?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="400" minHeight="300" applicationComplete="application1_applicationCompleteHandler(event)">
- <s:layout>
- <s:BasicLayout/>
- </s:layout>
- <fx:Script>
- <![CDATA[
- import mx.core.IVisualElement;
- import mx.events.FlexEvent;
- import mx.events.ModuleEvent;
- import mx.modules.IModuleInfo;
- import mx.modules.ModuleManager;
- import mx.controls.Alert;
- private var module:IModuleInfo;
- private var first:Boolean=true;//是否首次加载的判断标志
- private var moduleInstance:Object;//用于保存加载后的实例引用
- protected function button1_clickHandler(event:MouseEvent):void
- {
- //非首次加载(先卸载)
- if (!first)
- {
- module.unload();
- pnl.removeElement(moduleInstance as IVisualElement);
- }
- initModule();
- module.load();
- btn1.enabled = false;
- }
- private function onModuleReady(e:ModuleEvent):void
- {
- moduleInstance = e.module.factory.create();//注:这里千万不能用as做任何的转型,否则就报null object reference错误,原因不明
- this.pnl.addElement(moduleInstance as IVisualElement);
- }
- private function initModule():void
- {
- module = ModuleManager.getModule("module1.swf");
- module.addEventListener(ModuleEvent.READY,onModuleReady);
- }
- //应用加载完成时,就预先将Module初始化(甚至这时就可以load,只是不显示而已,以改善用户体验)
- protected function application1_applicationCompleteHandler(event:FlexEvent):void
- {
- initModule();
- }
- ]]>
- </fx:Script>
- <s:Panel id="pnl" title="动态加载Module" left="10" top="10" bottom="50" right="10"></s:Panel>
- <s:Button click="button1_clickHandler(event)" label="load" horizontalCenter="0" bottom="10" id="btn1">
- </s:Button>
- </s:Application>