Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- typealias block = () -> ()
- class NotificationCenter {
- static let shared = NotificationCenter()
- var map :[String: [(AnyObject, block)]]
- private init(){
- map = [String: [(AnyObject, block)]]()
- }
- func addObserver(_ event: String, _ handle : @escaping block, _ target: AnyObject){
- let pair = (target, handle)
- map[event, default:[(AnyObject, block)]()].append(pair)
- }
- func postEvent(_ event: String){
- if let list = map[event]{
- for pair in list {
- pair.1()
- }
- }
- }
- func removeObserver(_ event: String, _ target: AnyObject) {
- if let list = map[event]{
- map[event] = list.filter{ $0.0 !== target}
- }
- }
- }
- class obj {
- }
- let o1 = obj()
- let o2 = obj()
- NotificationCenter.shared.addObserver("event1", {
- print("obj1 - event 1")
- }, o1)
- NotificationCenter.shared.addObserver("event1", {
- print("obj2 - event 1")
- }, o2)
- NotificationCenter.shared.addObserver("event2", {
- print("obj2 - event 2")
- }, o2)
- NotificationCenter.shared.postEvent("event1")
- NotificationCenter.shared.postEvent("event2")
- print()
- NotificationCenter.shared.removeObserver("event1", o1)
- NotificationCenter.shared.postEvent("event1")
- NotificationCenter.shared.postEvent("event2")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement