Created
February 26, 2010 03:19
-
-
Save rjungemann/315357 to your computer and use it in GitHub Desktop.
Simple Ruby event dispatcher
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
# simple event dispatcher implementation | |
module Evented | |
class Dispatcher < Array | |
def call *args; self.each do |e|; e.call *args end end | |
end | |
class Dispatchers < Hash | |
def call name, *args; self[name].call(*args) if self[name] end | |
end | |
def dispatchers; @dispatchers ||= Dispatchers.new end | |
def dispatcher name; dispatchers[name] ||= Dispatcher.new end | |
end | |
#class Cow | |
# include Evented | |
# | |
# attr_reader :name | |
# | |
# def initialize name = nil; @name = name end | |
# def moo; dispatcher("mooed").call self end | |
#end | |
# | |
#cow = Cow.new "Betsy" | |
#cow.dispatchers("mooed") << lambda { |c| puts "#{c.name} mooed." } | |
#cow.moo |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I have created a little more complete version of an event dispatcher system : https://github.com/ThatAmine/event_dispatcher
I hope that it might be useful for someone.