-
Notifications
You must be signed in to change notification settings - Fork 0
/
README
74 lines (58 loc) · 2.44 KB
/
README
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
The EventPublisher module enables you to define multiple events in a class, and have objects subscribe to them with either a Method instance, or a block. Subscribers can obviously also unsubscribe Method instances, though blocks can't be unsubscribed.
To install, simply type this:
gem install eventpublisher
Here's a simple example that illustrates the usage of the EventPublisher module:
class Publisher
include EventPublisher
event :first_event
event :second_event
def trigger_events
trigger :first_event, "first event"
trigger :second_event, "second event", "extra argument"
end
end
class FirstSubscriber
def initialize(publisher)
@publisher = publisher
@publisher.subscribe_all self
end
def stop_listening
@publisher.unsubscribe_all self
end
def first_event_handler(args)
puts "first_event_handler of FirstSubscriber received #{args}"
end
def second_event_handler(arg1, arg2)
puts "second_event_handler of FirstSubscriber received arg1 = #{arg1} arg2 = #{arg2}"
end
end
class SecondSubscriber
def initialize(publisher)
@publisher = publisher
@publisher.subscribe :first_event, method(:first_handler)
@publisher.subscribe(:second_event) { |arg1, arg2| puts "block from SecondSubscriber received: #{arg1} #{arg2}"}
end
def stop_listening
@publisher.unsubscribe :first_event, method(:first_handler)
end
def first_handler(args)
puts "first_handler of SecondSubscriber received #{args}"
end
end
publisher = Publisher.new
first_subscriber = FirstSubscriber.new(publisher)
second_subscriber = SecondSubscriber.new(publisher)
puts "you should see 4 outputted strings when the events are triggered"
publisher.trigger_events
first_subscriber.stop_listening
second_subscriber.stop_listening
puts "you should still see 1 outputted string because the block is still subscribed, while the Method instances have been unsubscribed"
publisher.trigger_events
The output of running this code is the following:
you should see 4 outputted strings when the events are triggered
first_event_handler of FirstSubscriber received first event
first_handler of SecondSubscriber received first event
second_event_handler of FirstSubscriber received arg1 = second event arg2 = extra argument
block from SecondSubscriber received: second event extra argument
you should still see 1 outputted string because the block is still subscribed, while the Method instances have been unsubscribed
block from SecondSubscriber received: second event extra argument