Emittr
Emittr is a event emitter for Ruby.
Installation
Add this line to your Gemfile:
gem 'emittr'
Or install it yourself as:
$ gem install emittr
Usage
Emittr can be used in two ways. You can just create an Emittr::Emitter instance and use it to emit and listen to events, like this:
emitter = Emittr::Emitter.new
emitter.on :user_connected do |user_name|
puts "Hello, #{user_name}"
end
emitter.emit :user_connected, 'Mr. Anderson'
Or you can include the Emittr::Events module into an existent class to make it an event emitter:
class Server
include Emittr::Events
def initialize
on(:user_connected) do |user_data|
handle_new_connection(user_data)
end
end
def handle_new_connection(user_data)
# do something clever here
end
end
server = Server.new
server.emit :user_connected, { name: 'Somebody', ip: '127.0.0.1' }
Add event listeners
#on(event, callback)
Call callback when event is emitted.
#once(event, callback)
Call callback when event is emitted for the first time, then the callback is removed from the listeners list of the given event.
#on_any(callback)
Call callback whenever an event is emitted.
#once_any(callback)
Call callback the first time any event is emitted then removes it from list.
Remove event listeners
#off(event, callback)
Remove callback from event callbacks list.
#off(event)
Removes all callbacks for event.
#off
Removes all callbacks for all events.
#off_any(callback)
Remove callback from list to be run after any event is emitted.
Emitting events
#emit(type, *args)
Emit an event with all passed args as params.
Retrieving added events
#listeners_for(event)
Return all callbacks for event. Callbacks added with #on_any or #once_any will not be included.
#listeners_for_any
Return all callbacks added with #on_any or #once_any
Contributing
- Fork it
- Create your feature branch (
git checkout -b my-new-feature) - Commit your changes (
git commit -am 'Add some feature') - Push to the branch (
git push origin my-new-feature) - Create new Pull Request
License
The gem is available as open source under the terms of the MIT License.