Skip to content

Instantly share code, notes, and snippets.

@clicube
Created June 13, 2012 06:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save clicube/2922440 to your computer and use it in GitHub Desktop.
Save clicube/2922440 to your computer and use it in GitHub Desktop.
Event Handler for ruby
# coding: utf-8
class EventHandler
def initialize
@methods = []
end
def add(method)
if !@methods.include?(method)
@methods << method
end
return self
end
alias << add
def delete(method)
if @methods.include?(method)
@methods.delete method
end
return self
end
def notify(*args)
@methods.dup.each do|method|
# dupしてるのは,呼び出した先でこのイベントハンドラに登録されるとeachがおかしくなるため.
method.call(*args)
end
end
end
if $0 == __FILE__
class ClassA
attr_reader :event
def initialize
@event = EventHandler.new
end
def some_event
@event.notify
end
end
class ClassB
def initialize class_a
class_a.event << method(:class_a_event)
end
def class_a_event
puts "event is handled"
end
end
class_a = ClassA.new
class_b = ClassB.new(class_a)
class_a.some_event
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment