Module: Triton::Messenger
Overview
Defined Under Namespace
Modules: Emittable, Listenable Classes: Listener
Instance Method Summary collapse
-
#add_listener(type, once = false, &callback) ⇒ Object
(also: #on)
Register the given block to be called when the events of type
type
will be emitted. -
#emit(type, sender = nil, *args) ⇒ Object
Emit an event of type
type
and call all the registered listeners to this event. -
#listeners ⇒ Object
this makes @listeners to be auto-initialized and accessed read-only.
-
#once(type, &callback) ⇒ Object
Register the given block to be called only once when the events of type
type
will be emitted. -
#remove_all_listeners(type = nil) ⇒ Object
Unregister all the listener for the
type
events. -
#remove_listener(listener) ⇒ Object
Unregister the given block.
Instance Method Details
#add_listener(type, once = false, &callback) ⇒ Object Also known as: on
Register the given block to be called when the events of type type
will be emitted. if once
, the block will be called once
20 21 22 23 24 25 26 |
# File 'lib/triton/messenger.rb', line 20 def add_listener(type, once=false, &callback) listener = Listener.new(type, callback, once) listeners[type] ||= [] listeners[type] << listener emit(:new_listener, self, type, once, callback) listener end |
#emit(type, sender = nil, *args) ⇒ Object
Emit an event of type type
and call all the registered listeners to this event. The sender
param will help the listener to identify who is emitting the event. You can pass then every additional arguments you’ll need
57 58 59 |
# File 'lib/triton/messenger.rb', line 57 def emit(type, sender=nil, *args) listeners[type].each { |l| l.fire(sender, *args) } if listeners.has_key? type end |
#listeners ⇒ Object
this makes @listeners to be auto-initialized and accessed read-only
14 15 16 |
# File 'lib/triton/messenger.rb', line 14 def listeners # this makes @listeners to be auto-initialized and accessed read-only @listeners ||= Hash.new end |
#once(type, &callback) ⇒ Object
Register the given block to be called only once when the events of type type
will be emitted.
31 32 33 |
# File 'lib/triton/messenger.rb', line 31 def once(type, &callback) add_listener(type, true, &callback) end |
#remove_all_listeners(type = nil) ⇒ Object
Unregister all the listener for the type
events. If type
is omitted, unregister all the listeners.
46 47 48 49 50 51 52 |
# File 'lib/triton/messenger.rb', line 46 def remove_all_listeners(type=nil) if type listeners.delete(type) else listeners.clear end end |
#remove_listener(listener) ⇒ Object
Unregister the given block. It won’t be call then went an event is emitted.
36 37 38 39 40 41 42 |
# File 'lib/triton/messenger.rb', line 36 def remove_listener(listener) type = listener.type if listeners.has_key? type listeners[type].delete(listener) listeners.delete(type) if listeners[type].empty? end end |