A mixin granting simple event firing and handler binding.
Binds an event handler, which is a Hash of the form:
{ :evid => Symbol, :id => Symbol, :repeat => Boolean, :proc => Proc }
See on and once for sugar.
# File lib/safubot/evented.rb, line 10 def bind(evid, handler) @handlers ||= {} @handlers[evid] ||= {} handler[:evid] = evid handler[:id] ||= @handlers[evid].length @handlers[evid][handler[:id]] = handler end
Fires an evid event with the given arguments.
# File lib/safubot/evented.rb, line 36 def emit(evid, *args) return unless @handlers && @handlers[evid] @handlers[evid].each do |id, handler| begin handler[:proc].call(*args) ensure @handlers[evid].delete(id) if !handler[:repeat] end end end
Binds a block to the specified event id. Returns the bound handler.
# File lib/safubot/evented.rb, line 25 def on(evid, opts={}, &callback) bind(evid, { :repeat => true, :proc => callback }.merge(opts)) end
Binds a block to the specified event id, to be executed only once. Returns the bound handler.
# File lib/safubot/evented.rb, line 31 def once(evid, opts={}, &callback) bind(evid, { :repeat => false, :proc => callback }.merge(opts)) end
Unbinds the given handler.
# File lib/safubot/evented.rb, line 19 def unbind(handler) @handlers[handler[:evid]].delete(handler[:id]) end