SWF间的双向通信

 假设有一个主 SWf 名为 main.swf 加载一个名为 game.swf 的游戏模块:
1. main 里面使用 Loader 将 game.swf 加载进来;
2. 在 game 中定义 public function moveBall(speed:Number) 方法,用于开始游戏;
3. 在 main 里面使用类似 loader["content"].moveBall(speed) 的语句调用 game.swf 里面的方法;
4. game.swf 与 main.swf 通信的方法,可以使用 dispatchEvent 方法与 main.swf 通信,也可以继续使用上述方法。

下面请看示例:
1. 首先创建被调用的 game.swf:
package {
    import flash.display.Sprite;
    import flash.events.Event;
    import flash.system.Security;

    public class Game extends Sprite {
        private var ball:Sprite;
        private var speed:Number;
       
        public function Game() {
            // 在 Flash IDE 中执行 Debug
            Security.allowInsecureDomain("*");
           
            if (stage) init();
            else addEventListener(Event.ADDED_TO_STAGE, init);
        }
       
        private function init(e:Event = null):void {
            removeEventListener(Event.ADDED_TO_STAGE, init);
            ball = new Sprite();
            ball.graphics.beginFill(0xFF0000);
            ball.graphics.drawCircle(0, 0, 50);
            ball.graphics.endFill();
            addChild(ball);
            ball.x = 50;
            ball.y = stage.stageHeight / 2;
        }
       
        public function moveBall(speed:Number):void {
            this.speed = speed;
            addEventListener(Event.ENTER_FRAME, onGameLoop);
        }
       
        private function onGameLoop(e:Event):void {
            ball.x += speed;
        }
       
        public function stopMove():void {
            removeEventListener(Event.ENTER_FRAME, onGameLoop);
        }
    }
}
在这个类里创建了一个小球实例 ball,还提供了两个公开的方法 moveBall(speed) 和 stopMove(),用于控制小球的运动与停止。最后,编译该文件将生成好的 game.swf 放到应用服务器的根目录上(http://localhost/game.swf)。

2. 下面创建主程序,调用 game.swf 并与其通信
package {
    import flash.display.Loader;