Type-safe event handling for Swift
https://github.com/aleclarson/emitter-kit.git
A replacement for NSNotificationCenter#addObserver and NSObject#addObserver that is type-safe and not verbose.
import EmitterKit
// A generic event emitter (but type-safe)!
var event = Event<T>()
// Any emitted data must be the correct type.
event.emit(data)
// This listener will only be called once.
// You are *not* required to retain it.
event.once { data: T in
print(data)
}
// This listener won't stop listening;
// unless you stop it manually,
// or its Event<T> is deallocated.
// You *are* required to retain it.
var listener = event.on { data: T in
print(data)
}
// Stop the listener manually.
listener.isListening = false
// Restart the listener (if it was stopped).
listener.isListening = true
A target allows you to associate a specific AnyObject with an emit call. This is useful when emitting events associated with classes you can't add properties to (like UIView).
When calling emit with a target, you must also call on or once with the same target in order to receive the emitted event.
let myView = UIView()
let didTouch = Event<UITouch>()
didTouch.once(myView) { touch in
print(touch)
}
didTouch.emit(myView, touch)
The Notifier class helps when you are forced to use NSNotificationCenter (for example, if you want to know when the keyboard has appeared).
// You are **not** required to retain this after creating your listener.
var event = Notifier(UIKeyboardWillShowNotification)
// Handle NSNotifications with style!
listener = event.on { (notif: Notification) in
print(notif.userInfo)
}
// Any NSObject descendant will work.
var view = UIView()
// "Make KVO great again!" - Donald Trump
listener = view.on("bounds") { (change: Change<CGRect>) in
print(change)
}
โ ๏ธ None of the classes in EmitterKit are thread-safe!
The following actions must be done on the same thread, or you need manual locking:
isListening property of a listenerEvent.getListeners methodNotificationListener class now takes a Notification instead of an NSDictionary.NotificationListener without a target will now receive every Notification with its name, regardless of the value of notif.object.Signal class was removed. (use Event<Void> instead)Emitter abstract class was removed.EmitterListener class was renamed EventListener<T>.Event<T> class no longer has a superclass.Notification class was renamed Notifier (to prevent collision with Foundation.Notification).on and once methods of Event<T> now return an EventListener<T> (instead of just a Listener)on and once methods of Notifier now return an NotificationListener (instead of just a Listener)on and once methods of NSObject now return an ChangeListener<T> (instead of just a Listener)keyPath, options, and object properties of ChangeListener<T> are now public.listenerCount: Int computed property was added to the Event<T> class.event: Event<T> property was added to the EventListener<T> class.