require 'observerext'
class Person
include Observer #include the observer related methods
observable :name,:address # the metavoodoo to create the accessor methods and fire events
end
admin=Person.new
admin.name='vagmi'
admin.address='admin@somesite.com'
# first observer
admin.observe :name do |old,newvalue|
puts %{The administrator changed from #{old} to #{newvalue}}
end
# the second observer
admin.observe :name do |old,newvalue|
puts 'there can be multiple observers'
end
admin.name='root'
#this prints the following statements
# > The administrator has changed from vagmi to root
# > there can be multiple observers
You can find the code for observerext.rb here. What I have basically done is to extend the Module class, which defines the observable method. The observable method injects the attributes' getters and setters. The setter method notifies the observers if there are any. The Observer module does the leg work of registering and unregistering the blocks and the notifyobservers method.
Update: Forgot to credit Greg Houston for explaining some of the ruby voodoo.
1 comment:
And how can a listener be removed?
Post a Comment