Skip to content

a lightweight tool to easily implement listener pattern

License

Notifications You must be signed in to change notification settings

Gujci/EventEmitter

Repository files navigation

EventEmitter

A lightweight tool to easily implement listener pattern.

Carthage compatible Build Status Swift

Example

Subscribe to events w parameters:

eventEmitterInstance.on("eventWithParameter") { (weak parameter: Any?) in
    //...
}

Or w/o parameters:

eventEmitterInstance.on("eventWithoutParameter") {
    //...
}

Defining events with an enum is also supported:

public enum AppEvent: String, Event {
    case some
    case other
}
eventEmitterInstance.on(AppEvent.some) {
    //...
}

Emit an event with an EventEmitter class

class EventEmitterClass: EventEmitter {
  var listeners: Dictionary<String, Array<Any>>? = [:]
  
  //...
  public func foo(parameter: Any?) {
    //...
    emit(AppEvent.some, information: parameter)
  }
  
  public func bar() {
    //...
    emit(AppEvent.some)
  }
}

Note: This is a protocoll so you can use it with structs as well.

String comforms to Event protocol, so this is also a valid code:

emit("some", information: parameter)

Documentation

Functions to be called from an EventEmitter instance

emit(_ event: Event)
emit<T>(_ event: Event, information: T)
emit(onMain event: Event)
emit<T>(onMain event: Event, information: T)

Functions to call on an EventEmitter instance

subscribe

on(_ event: Event, action: (() -> ()))
on(_ events: [Event], action: (() -> ()))
once(_ event: Event, action: (() -> ()))
on<T>(_ event: Event, action: ((T?) -> ()))
on<T>(_ events: [Event], action: ((T?) -> ()))
once<T>(_ event: Event, action: ((T?) -> ()))

unsubscribe

removeListeners(_ event: Event?)

Installation

SPM

Use the GitHub link in Xcode

Carthage

Put this line into your cartfile

github "Gujci/EventEmitter"

Swift 3

for Swift 3 use the 0.5.5 tag. This version will not be supported.

github "Gujci/EventEmitter" "== 0.5.5"

Debugging

To turn on logging add EventLoggingEnabled to 'Arguments passed on launch' at Schema/Run/Arguments

TODO

  • Travis support
  • Full code coverage
  • Support custom threads
  • Once
  • More documentation