Created
March 23, 2018 19:29
-
-
Save justinperkins/dadc8b707da4a1499f71610bbf584c55 to your computer and use it in GitHub Desktop.
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
class Event | |
def initialize | |
@callbacks = {} | |
end | |
def on(event, &block) | |
@callbacks[event] ||= [] | |
@callbacks[event] << block | |
end | |
def fire(event) | |
(@callbacks[event] || []).collect { |callback| | |
callback.call | |
callback | |
} | |
end | |
end | |
event = Event.new | |
event.on 'ping' do | |
puts 'pong' | |
end | |
event.on 'ping' do | |
puts 'kong' | |
end | |
puts 'firing ping' | |
event.fire('ping').each do |callback| | |
puts "calling callback again" | |
callback.call | |
end | |
puts 'firing poo' | |
event.fire('poo').each do |callback| | |
puts "calling callback again" | |
callback.call | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment