Skip to content

Instantly share code, notes, and snippets.

@tomconroy
Last active December 22, 2016 20:57
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomconroy/9f699d5207802427c46f to your computer and use it in GitHub Desktop.
Save tomconroy/9f699d5207802427c46f to your computer and use it in GitHub Desktop.
A simple Event Emitter for swift (use EmitterKit for something more robust)
class Event <T:Any> {
var handlers = Array<(T) -> Void>()
func listen(handler: (T) -> Void) {
handlers.append(handler)
}
func emit(object: T) {
for handler in handlers {
handler(object)
}
}
}
let didSomething = Event<String>()
didSomething.listen { str in
println(str)
}
didSomething.emit("Did it!")
# => "Did it!"
let tupleEvent = Event<(String, Int)>()
tupleEvent.listen { (str, num) in
doSomethingWith(str, num)
}
tupleEvent.emit("Example", 10)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment