Skip to content

Instantly share code, notes, and snippets.

@k0t0vich
Created August 1, 2019 20:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save k0t0vich/12db199f590f3cc16470ba8a5f68a085 to your computer and use it in GitHub Desktop.
Save k0t0vich/12db199f590f3cc16470ba8a5f68a085 to your computer and use it in GitHub Desktop.
Typed event listeners example In the beginning of this article we also mentioned the addEventListener function, so for the sake of completeness, let's also apply our new knowledge to it. Here, we use type parameter to specify listener function type:
import haxe.Constraints.Function;
abstract Event<T:Function>(String) {
public inline function new(name) {
this = name;
}
}
extern class EventEmitter {
function new();
function addEventListener<T:Function>(event:Event<T>, listener:T):Void;
}
class Main {
static inline var EVENT_START = new Event<Array<String>->Void>("start");
static inline var EVENT_EXIT = new Event<Int->Void>("exit");
static function main() {
var emitter = new EventEmitter();
// arr is inferred as Array<String>
emitter.addEventListener(EVENT_START, function(arr) trace(arr));
// compile error: String -> Void should be Int -> Void
// emitter.addEventListener(EVENT_EXIT, function(s:String) {});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment