开发者

How does Action Script 3 handle Asynchronous callbacks?

I have a piece of code in my game which looks a lot like this:

MultiplayerAPI.createGameRoom(function(){ successFunction(new Object()); });        

Basically, the createGameRoom is performed and, upon success, the function I passed is r开发者_运维问答un.

However I've been running into some strange bugs recently and I'm wondering, is the instance of "new Object();" the same each time the callback function is run?

It needs to be a different, fresh instance of Object each time, but I'm having some garbage collection issues which make me think it's passing the same object each time that event callback is fired,

Anyone have any idea how Flash handles this?


in your example you call the method successFunction within the definition and not when the code should be executed. You have to pass a reference to the method instead of invoking it. Take a look at the following examples. If you use the apply method you can pass the arguments as Array. *Nicholas

Function Reference & Function Call

function myFunction(parameter:String):String
{
    return 'hello '+parameter;
}

var myFunctionReference:Function = myFunction;
trace(myFunctionReference); // function Function() {}

trace(myFunctionReference('world')); // 'hello world'

var myFunctionReturnValue:String = myFunction('moon');
trace(myFunctionReturnValue); // 'hello moon'

Working Example

package
{
    import flash.display.Sprite;

    public class MethodTest extends Sprite
    {   
        public function MethodTest()
        {
            trace('MethodTest Constructor');
            trace('---');
            invoke(successFunction,'first',{id:123,type:'foo'}); 
            trace('---');
            invokeByApply(successFunction,'second',{id:456,type:'bar'});   
        }

        public function invoke(method:Function,someName:String, someObject:Object):void{
            trace('MethodTest invoke');
            method(someName,someObject);
        }

        public function invokeByApply(method:Function,...arguments):void{
            trace('MethodTest invokeByApply');
            method.apply(null,arguments);
        }

        public function successFunction(someName:String, someObject:Object):void{           
            trace('MethodTest successFunction');
            trace('someName: '+someName);
            for(var key:String in someObject)trace(key+': '+someObject[key]);

        }
    }
}


Writing AS3 code as in the example you gave (defining new functions from within the calls to other methods), as is done in JavaScript, you will find it very difficult to debug.

I suggest checking out "OOP with ActionScript" by Hall/Wan and taking advantage of object orientated programming design principles, as it may make your life easier in the long term:

http://www.amazon.com/Object-Oriented-Programming-ActionScript-Branden-Hall/dp/0735711836

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜