Last active
September 8, 2016 08:41
-
-
Save zaynyatyi/9898ce2193ccfd93c9831776317f6bea to your computer and use it in GitHub Desktop.
Just a simple test of typed event system in haxe using abstract
This file contains hidden or 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
| abstract DataEvent<T>(String) to String | |
| { | |
| public inline function new(name) this = name; | |
| } | |
| typedef Handler<T> = T->Void; | |
| class GlobalDispatcher | |
| { | |
| static var eventToHandlers = new Map<String,Array<Handler<Dynamic>>>(); | |
| public static function addListenerAdvanced<T>(event:DataEvent<T>, callback:T->Void):Void | |
| { | |
| var listener:Handler<T> = callback; | |
| if(!eventToHandlers.exists(event)) eventToHandlers.set(event,[]); | |
| var handlers = eventToHandlers.get(event); | |
| handlers.push(listener); | |
| } | |
| public static function dispatchAdvanced<T>(event:DataEvent<T>, param:T):Void | |
| { | |
| if (eventToHandlers.exists(event)) { | |
| var handlers = eventToHandlers.get(event); | |
| for (handler in handlers) { | |
| handler(param); | |
| } | |
| } | |
| } | |
| } | |
| class Test { | |
| static function main() { | |
| new Test(); | |
| } | |
| public function new() | |
| { | |
| var eventInt = new DataEvent<Int>("testInt"); | |
| var eventString = new DataEvent<String>("testString"); | |
| GlobalDispatcher.addListenerAdvanced( | |
| eventInt, | |
| handleInt | |
| ); | |
| GlobalDispatcher.addListenerAdvanced( | |
| eventString, | |
| handleString | |
| ); | |
| GlobalDispatcher.dispatchAdvanced(eventInt, 0); | |
| // if event will be without <T> it will work because our event will be not typed | |
| // with typed event it will throw compilation error | |
| //GlobalDispatcher.dispatchAdvanced(eventInt, "test"); //error | |
| GlobalDispatcher.dispatchAdvanced(eventString, "test"); | |
| } | |
| function handleInt(data:Int):Void | |
| { | |
| trace("int data: ", data); | |
| } | |
| function handleString(data:String):Void | |
| { | |
| trace("string data: ", data); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment