module Tardvig::Events
The mixin gives ability to have events @see en.wikipedia.org/wiki/Event_%28computing%29
Public Instance Methods
happen(event, data = nil)
click to toggle source
Executes all the listeners which are bound to the given event name @param data [Object] the object will be passed as an argument to the
listeners
# File lib/tardvig/events.rb, line 37 def happen(event, data = nil) listeners(event).clone.each do |listener| listener.call(data) end end
Also aliased as: trigger
listeners(event)
click to toggle source
@return [Array] array with all the listeners which are bound to the given
event name
# File lib/tardvig/events.rb, line 47 def listeners(event) @listeners ||= {} @listeners[event] ||= [] end
on(event, &listener)
click to toggle source
Binds given listener (handler/callback) to given event name @param event [Object] any custom identificator. Your listener will be
executed only when you trigger event with this identificator.
@param listener [#call] this object will be executed (through the call
method) when you trigger the given event.
# File lib/tardvig/events.rb, line 10 def on(event, &listener) listeners(event) << listener end
on_first(event, &listener)
click to toggle source
Does the same as {#on}, but the listener will be executed only once, then it will be deleted. @param (see on
)
# File lib/tardvig/events.rb, line 17 def on_first(event, &listener) throwaway_callback = proc do |*args| remove_listener event, throwaway_callback listener.call(*args) end listeners(event) << throwaway_callback end
remove_listener(event, listener = nil)
click to toggle source
Unbinds given listener from the given event name
# File lib/tardvig/events.rb, line 26 def remove_listener(event, listener = nil) if listener.nil? listeners(event).clear else listeners(event).delete listener end end