Skip to content

Instantly share code, notes, and snippets.

@Evertt
Last active March 26, 2016 22:27
Show Gist options
  • Save Evertt/339d0eda49018c2f1b8b to your computer and use it in GitHub Desktop.
Save Evertt/339d0eda49018c2f1b8b to your computer and use it in GitHub Desktop.
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