Module: Listenable

Overview

module to implement simple event handling and notifying

Instance Method Summary collapse

Instance Method Details

#add_listener(identification, listener) ⇒ Object

method to add a listener which wants to be notified when a given event is triggered

Parameters:

  • identification (Symbol)

    an identification for the listener

  • listener (Object)

    the listener object that should be added as a new listener



16
17
18
# File 'lib/event/listenable.rb', line 16

def add_listener(identification, listener)
  listeners[identification] = listener
end

#listenersHash

method to get get alle listener or create a new Hash, when not listener is present

Returns:

  • (Hash)

    the hash for storing listener to an object



7
8
9
# File 'lib/event/listenable.rb', line 7

def listeners
  @listeners ||= Hash.new()
end

#notify_listeners(event_name, *args) ⇒ Object

method to send a notification to all listeners which respond to the given event



27
28
29
30
31
32
33
# File 'lib/event/listenable.rb', line 27

def notify_listeners(event_name, *args)
  listeners.each_value { |listener|
    if listener.respond_to?(event_name)
      listener.__send__(event_name, *args)
    end
  }
end

#remove_listener(listener) ⇒ Object

method to remove a given listener from the list of listener objects



21
22
23
# File 'lib/event/listenable.rb', line 21

def remove_listener(listener)
  listeners.delete(listener)
end