Created
December 18, 2012 02:41
-
-
Save aackerman/4324527 to your computer and use it in GitHub Desktop.
JS style event emitter in Ruby
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 EventEmitter | |
def initialize() | |
@callbacks = {} | |
end | |
def on(event, &callback) | |
@callbacks[event] ||= [] | |
@callbacks[event].push(callback) | |
end | |
def off(event) | |
@callbacks[event] = nil; | |
end | |
def emit(event, *args) | |
if @callbacks[event] | |
@callbacks[event].each do |callback| | |
callback.call args | |
end | |
end | |
end | |
end |
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
require './EventEmitter' | |
ev = EventEmitter.new | |
ev.on('hello') { |*args| | |
args.each { |arg| | |
puts arg | |
} | |
} | |
ev.emit('hello', 'world', 'it\'s', 'december', 'almost', 'christmas', 'time', 'for', 'presents') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment