Created
June 13, 2012 06:59
-
-
Save clicube/2922440 to your computer and use it in GitHub Desktop.
Event Handler for 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
# 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