EventSpitter vs. Observable
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# We only care about Tick and Alarm events. | |
# The Alarm event should only be handled once. | |
# All other events should be ignored. | |
require 'observer' | |
class Clock | |
include Observable | |
def tick | |
changed | |
notify_observers('tick', Time.now) | |
end | |
def alarm | |
changed | |
notify_observers('alarm', Time.now) | |
end | |
def snooze | |
changed | |
notify_observers('snooze', Time.now) | |
end | |
end | |
class Something | |
attr_reader :alarm_sounded | |
def update(what, value) | |
case what | |
when 'tick' | |
puts 'Tick...' | |
when 'alarm' | |
unless alarm_sounded | |
@alarm_sounded = true | |
puts 'Alarm!' | |
end | |
else | |
puts "I don't care about #{what}" | |
end | |
end | |
end | |
clock = Clock.new | |
something = Something.new | |
clock.add_observer(something) | |
clock.tick | |
# => Tick... | |
clock.alarm | |
# => Alarm! | |
clock.snooze | |
# => I don't care about snooze | |
clock.alarm | |
# => | |
clock.tick | |
# => 'Tick...' |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# We only care about Tick and Alarm events. | |
# The Alarm event should only be handled once. | |
# All other events should be ignored. | |
require 'event_spitter' | |
class Clock | |
include EventSpitter | |
def tick | |
emit('tick', Time.now) | |
end | |
def alarm | |
emit('alarm', Time.now) | |
end | |
def snooze | |
emit('snooze', Time.now) | |
end | |
end | |
clock = Clock.new | |
clock.on('tick', ->(time) { puts 'Tick...' }) | |
clock.once('alarm',->(time) { puts 'Alarm!' }) | |
clock.tick | |
# => Tick... | |
clock.alarm | |
# => Alarm! | |
clock.snooze | |
# => | |
clock.alarm | |
# => | |
clock.tick | |
# => Tick... | |
# EventSpitter works with anything that responds to #call. | |
def ticker(time) | |
puts 'Ticker...' | |
end | |
clock.on('tick', method(:ticker)) | |
clock.tick | |
# => Tick... | |
# => Ticker... |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment