Skip to content

Instantly share code, notes, and snippets.

@frekw
Created March 22, 2009 01:59
Show Gist options
  • Save frekw/83038 to your computer and use it in GitHub Desktop.
Save frekw/83038 to your computer and use it in GitHub Desktop.
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