Saturday, April 02, 2011

Simple Event Manager in Ruby

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
class Event
USER_CONNECTED = 1
SERVER_CONNECTED = 2
end

class Listener
def onEvent(event,params=[])
puts event
end
end

class EventManager
def initialize()
@listenersMap = Hash.new
end

def subscribe(event,listener)
listeners = @listenersMap[event]
if listeners == nil
@listenersMap[event] = Array.new
else
if @listenersMap[event].include?(listener)
return
end
end
@listenersMap[event].push(listener)
end

def notify(event)
if @listenersMap[event] != nil
@listenersMap[event].each do |lis|
lis.onEvent(event)
end
end
end
end

puts "Initializing the event manager"
lis = Listener.new
manager = EventManager.new
manager.subscribe(Event::USER_CONNECTED,lis)
manager.subscribe(Event::USER_CONNECTED,lis)
manager.notify(Event::USER_CONNECTED)