Skip to content

Instantly share code, notes, and snippets.

@fkaa
Created June 7, 2014 19:20
Show Gist options
  • Select an option

  • Save fkaa/213fff8b8f3f3cb820e2 to your computer and use it in GitHub Desktop.

Select an option

Save fkaa/213fff8b8f3f3cb820e2 to your computer and use it in GitHub Desktop.
module Listener
def on(*types, &blk)
types.each do |type|
(self.listeners[type] ||= []) << blk
end
end
def trigger(event)
return unless self.listeners[event.type]
self.listeners[event.type].each do |blk|
blk.call(event)
end
end
private
def listeners
@listeners ||= {}
end
end
class Event
attr_reader :type
def initialize(type)
@type = type;
end
end
class Foo
include Listener
end
foo = Foo.new
foo.on :bar do |event|
puts 'inside :bar event!'
end
foo.trigger(Event.new(:bar))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment