开发者

AS3: How to force parameters in callback functions

I am currently doing something like this:

myFunc(tracer);

function tracer(message:String):void{
 trace(message);
}

function myFunc(callback:Function):void{
 callback("Hello");
}

Now, this works fine. But how can the function myFunc know, if the g开发者_运维知识库iven callback function accepts the correct number and type of arguments in its signature?

I want to avoid that I call something like this somewhere in my code:

myFunc(tracer2);

function tracer2():void{
 trace("done");
}

function myFunc(callback:Function):void{
 // Argument mismatch!
 callback("Hello");
}

Is there a way to do something like this, in order to use compiler warnings/error messages and thus avoid exceptions at runtime?

// Won't work :-(
function myFunc(callback(message:String):Function):{
 callback("Hello");
}


My understanding is that this is a situation that can only be caught at runtime. AS3 offers no mechanism for this kind of type-checking. I would suggest that if this is important, that you get compile-time checking by passing an object with a strongly typed interface rather than simply passing a function, where the type information you need will be lost.


I think you can add a second parameter in myFunc that will give information on what parameters are expected to be sent to the callback function. That way you could have myFunc(tracer2,"null") in one place and myFunc(tracer,"String") at another place.

I would try something like

function myFunc(callback:Function, ParamRequest:Array /* of String */ ):void{
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜