Created
March 22, 2009 01:59
-
-
Save frekw/83038 to your computer and use it in GitHub Desktop.
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
class Model | |
attr_accessor :x | |
def initialize | |
@observers ||= {} | |
end | |
def observe(key, callback = nil, &blk) | |
@observers[key] ||= [] | |
if block_given? | |
@observers[key] << blk | |
end | |
return if callback.nil? | |
@observers[key] << callback | |
end | |
def remove_observer(key, callback) | |
@observers[key].delete(callback) | |
end | |
def x=(x) | |
@x = x | |
notify(:x, @x) | |
end | |
private def notify(key, value) | |
@observers[key].each { |callback| callback.call(value) } | |
end | |
end | |
m = Model.new | |
m.observe(:x) do |update| | |
puts "updated from block (update is: #{update})" | |
end | |
callback = lambda { |update| puts "updated from lambda (update is :#{update})" } | |
m.observe(:x, callback) | |
m.x = 2 | |
m.remove_observer(:x, callback) | |
m.x = 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment