INSTALL:
% gem install event_emitter
REQUIREMENTS:
- Ruby 1.8.7+
- Ruby 1.9.2+
- JRuby 1.6.7+
SYNOPSIS:
setup
load rubygem
require "rubygems"
require "event_emitter"
include EventEmitter in class definition
class User
include EventEmitter
attr_accessor :name
end
on/emit
regist event listener
user = User.new
user.name = "shokai"
user.on :go do |data|
puts "#{name} go to #{data[:place]}"
end
call event
user.emit :go, {:place => "mountain"}
# => "shokai go to mountain"
once
regist event using "once"
user.once :eat do |what, where|
puts "#{name} -> eat #{what} at #{where}"
end
call only once
user.emit :eat, "BEEF", "zanmai" # => "shokai -> eat BEEF at zanmai"
user.emit :eat, "Ramen", "marutomo" # => do not call.
remove listener
remove event listener by nameuser.remove_listener :go
event_id = user.on :go do |data|
puts "#{name} go to #{data[:place]}"
end
user.remove_listener event_id
Instance-Specific Method
apply as instance-specific method
class User
end
shokai = User.new
ymrl = User.new
EventEmitter.apply shokai ## set Instance-specific Method
shokai.on :go do |data|
puts "go to #{data[:place]}"
end
shokai.emit :go, :place => "chiba city"
# => "go to chiba city"
ymrl.on :go do |data| # => raise "undefined-method Error"
puts "go to #{data[:place]}"
end
Class Method
apply as class method
class DB
def self.connect
self.emit :connect, "db_connected"
end
end
EventEmitter.apply DB ## set Class Method
DB.on :connect do |status|
puts status
end
DB.connect # => "db_connected"