Created
March 22, 2009 14:04
-
-
Save frekw/83176 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 | |
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 self.observable(*observables) | |
observables.each do |obs| | |
self.class_eval do | |
alias_method "no_callback_#{obs.to_s}=", "#{obs.to_s}=" | |
define_method "#{obs.to_s}=" do |value| | |
send "no_callback_#{obs.to_s}=", value | |
notify(obs.to_sym, value) | |
end | |
end | |
end | |
return nil | |
end | |
def notify(key, value) | |
@observers[key].each { |callback| callback.call(value) } | |
end | |
end | |
class Foo < Model | |
attr_accessor :x, :y | |
observable :x, :y | |
end | |
m = Foo.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.observe(:y, callback) | |
m.y = 1 | |
m.remove_observer(:x, callback) | |
m.x = 1 | |
m.y = 2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment