Created
August 1, 2019 20:37
-
-
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:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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