在主程序中用SWFLoader载入了一个SWF子程序,如何实现两个程序间的参数传递与方法调用?
共用一个单例对象进行事件派发,通过事件传递参数
首先,你得有一个单例的事件派发器:
- package
- {
- import flash.events.EventDispatcher;
-
- public class Dispatcher extends EventDispatcher
- {
- private static var instance:Dispatcher;
-
- public static function getInstance():Dispatcher
- {
- if (instance == null)
- {
- instance = new Dispatcher();
- }
- return instance;
- }
- }
- }
复制代码
然后,写自定义事件:
- package
- {
- import flash.events.Event;
- public class MyEvent extends Event
- {
- public static const TEST_EVENT:String = "test.event";
-
- public var data:*;
-
- public function MyEvent(eventType:String, data:* = null)
- {
- super(eventType);
- this.data = data;
- }
- }
- }
复制代码
单例派发器通过getInstance()函数获得:
- var dispatcher:Dispatcher = Dispatcher. getInstance();
复制代码
子模块通过dispatcher派发事件:
- dispatcher.dispatchEvent(new MyEvent(MyEvent.TEST_EVENT, "test"));
复制代码
主模块通过dispatcher监听事件:
- dispatcher.addEventListener(MyEvent.TEST_EVENT, getEventHandler);
- function getEventHandler(e:MyEvent):void
- {
- trace(e.data);
- }
复制代码
同样子模块里面也可以这样监听来自主模块的事件