as3回调方法模拟事件监听

//=================Client.as ==============
package callback{
    import flash.display.Sprite;
    
    public class Client extends Sprite{
        public function Client() {
            //调用Seriver类的callFun方法,并把clientFun方法传给callFun方法
            var server : Server = new Server();
            server.callFun(clientFun);
        }
        
        //定义一个回调方法让Server中的callFun来调用
        public function clientFun() : void{
            trace("I am a callback function defiend by Client");
        }
        
    }
}

//===================Server.as==============
package callback{
    import flash.display.Sprite;
    import flash.utils.setTimeout;
    
    public class Server extends Sprite{
        public function Server() {
            super();
        }
        
        //接收Client类传入的方法
        public function callFun(arg : Function) : void{
            trace("I am a server method.....");
            //先做一些事情
            setTimeout(showMsg, 1000);
            
            //调用Client类传过来的方法
            setTimeout(arg, 3000);
        }
        
        private function showMsg() : void{
            trace("do some stuff on server..........");
        }
    }
}

 

posted @ 2012-10-17 11:24  playerlife  阅读(913)  评论(0编辑  收藏  举报