Module: Triton::Messenger

Extended by:
Messenger
Included in:
Messenger
Defined in:
lib/triton/messenger.rb

Overview

The Messenger module provides a simple event emitter/listener system

Example

require 'triton'

Triton::Messenger.on(:alert) { puts "alert!" }
Triton::Messenger.emit(:alert)
                    # -> alert!

Defined Under Namespace

Modules: Emittable, Listenable Classes: Listener

Instance Method Summary collapse

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



56
57
58
# File 'lib/triton/messenger.rb', line 56

def emit(type, sender=nil, *args)
  listeners[type].each { |l| l.fire(sender, *args) } if listeners.has_key? type
end

#listenersObject

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.



45
46
47
48
49
50
51
# File 'lib/triton/messenger.rb', line 45

def remove_all_listeners(type=nil)
  if type
    listeners.delete(type)
  else
    listeners.clear
  end
end

#remove_listener(type, listener) ⇒ Object

Unregister the given block. It won’t be call then went an event is emitted.



36
37
38
39
40
41
# File 'lib/triton/messenger.rb', line 36

def remove_listener(type, listener)
  if listeners.has_key? type
    listeners[type].delete(listener)
    listeners.delete(type) if listeners[type].empty?
  end
end