subscribe(msg:String, ?callback:Dynamic->Void);
You can also use this to type instead of using Dynamic
subscribe<T>(msg:String, callback:T->Void);
You could optimize this, by marking the function with the @:generic metadata, then the output generates all used combinations. For JavaScript target it's not needed to add this metadata.
> subscribe<T>(msg:String, callback:T->Void);
static function func(x:Int)
{
trace( untyped __cpp__("{0}->__ArgCount()", func ) );
}
Can function types (e.g. Int->Void) be passed as a Dynamic parameter?
If so, is it possible to introspect the number of arguments the function takes?
I'm building a quick pub/sub utility, and I want the callback functions to optionally take a data parameter.
In AS3 and JS, function objects have a length parameter that reports the number of parameters they accept:> var f = function(a, b) { return a+b;}> f.length2So is it possible for a subscribe function to accept functions of varying signature:function subscribe(channel:String, callback:Dynamic):Void{var num_params = callback.length;}subscribe("foo", function() { trace("I don't take parameters"); }subscribe("bar", function(msg:Dynamic) { trace("I do take parameters: "+msg); }Or do I have to write two different subscribe functions:function subscribe_none(channel:String, callback:Void->Void):Voidfunction subscribe_one(channel:String, callback:Dynamic->Void):Void
haxe.Function abstract to accept any callback signature
you can use .length in JS and $nargs in Neko (and maybe CPP?)
There is a hidden int __ArgCount member on hxcpp objects
I really think you should get rid of that stringly typed API. Here's a sketch:
abstract EventType<T>(String) {public inline function new(s) this = s;}interface Hub {public function publish<T>(event:EventType<T>, data:T):Void;public function subscribe(event:EventType<T>, handler:Callback<T>):CallbackLink;}class Toasting {static inline var DONE = new EventType<Array<Toast>>("Toasting::DONE");}
@:callable | |
abstract Function(Dynamic) { } | |
To give fair warning, I reserve the right to change this (__ArgCount) to something else (possibly double up with __length to save space) in the future.