Last active
March 26, 2016 22:27
-
-
Save Evertt/339d0eda49018c2f1b8b to your computer and use it in GitHub Desktop.
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
public protocol Event {} | |
public enum Listener<E: Event> { | |
public typealias T = E -> () | |
} | |
public protocol Dispatcher { | |
func listen<E: Event>(listener: Listener<E>.T) | |
func fire<E: Event>(event: E) | |
func push<E: Event>(event: E) | |
func flush() | |
} | |
public class TestDispatcher: Dispatcher { | |
var listeners = [String:[Any]]() | |
var pushedEvents = [(Event.Type, Event)]() | |
public init() {} | |
public func listen<E: Event>(listener: Listener<E>.T) { | |
var listeners = self.listeners[String(E.self)] ?? [] | |
listeners += [listener] as [Any] | |
self.listeners[String(E.self)] = listeners | |
} | |
public func fire<E: Event>(event: E) { | |
listeners[String(E.self)]?.forEach { | |
let f = $0 as! Listener<E>.T | |
f(event) | |
} | |
} | |
public func push<E: Event>(event: E) { | |
pushedEvents += [(E.self, event as Event)] | |
} | |
public func flush() { | |
for (type, event) in pushedEvents { | |
fire(event as type) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment