| Module | Listener |
| In: |
lib/webgen/listener.rb
|
Implementation of the listener pattern. The including class defines messages to which other classes can listen.
Usage example:
class Test
include Listener
def initialize
add_msg_name :test
end
def invoke( *param )
dispatch_msg( :test, *param )
end
end
t = Test.new
t.add_msg_listener( :test ) do |*param|
print param.inspect
end
t.invoke 'hello'
t.invoke 'lester', ['tsd', 4, 'test']
Adds a new message listener for the object. The message msgName will be dispatched to either the given callableObject (has to respond to call) or the given block. If both are specified the callableObject is used.
# File lib/webgen/listener.rb, line 57
57: def add_msg_listener( msgName, callableObject = nil, &block )
58: return unless defined?( @msgNames ) && @msgNames.has_key?( msgName )
59:
60: if !callableObject.nil?
61: raise NoMethodError, "listener needs to respond to 'call'" unless callableObject.respond_to? :call
62: @msgNames[msgName].push callableObject
63: elsif !block.nil?
64: @msgNames[msgName].push block
65: else
66: raise "you have to provide a callback object or a block"
67: end
68: end
Removes the given object from the dispatcher queue of the message msgName.
# File lib/webgen/listener.rb, line 72
72: def del_msg_listener( msgName, object )
73: @msgNames[msgName].delete object if defined? @msgNames
74: end
Adds a new message target called msgName
# File lib/webgen/listener.rb, line 83
83: def add_msg_name( msgName )
84: @msgNames = {} unless defined? @msgNames
85: @msgNames[msgName] = [] unless @msgNames.has_key? msgName
86: end
Deletes the message target msgName.
# File lib/webgen/listener.rb, line 90
90: def del_msg_name( msgName )
91: @msgNames.delete msgName if defined? @msgNames
92: end
Dispatches the message msgName to all listeners for this message, providing the given arguments
# File lib/webgen/listener.rb, line 97
97: def dispatch_msg( msgName, *args )
98: if defined? @msgNames and @msgNames.has_key? msgName
99: @msgNames[msgName].each do |obj|
100: obj.call( *args )
101: end
102: end
103: end