Skip to content

Instantly share code, notes, and snippets.

@aackerman
Created December 18, 2012 02:41
Show Gist options
  • Save aackerman/4324527 to your computer and use it in GitHub Desktop.
Save aackerman/4324527 to your computer and use it in GitHub Desktop.
JS style event emitter in Ruby
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
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