From: Gavin Kistner Date: 2004-09-28T12:56:25+09:00 Subject: Binding of the Caller (redux) I'm trying to use Florian's Binding.of_caller, and it ain't working. In the code below, if I uncomment the Binding.of_caller line, I get the error: ./libs/binding_of_caller.rb:61:in `of_caller': Binding.of_caller used in non-method context or trailing statements of method using it aren't in the block. (ArgumentError) Is there a better way to automatically store a reference to the method which invoked the current method? If not, can someone see what might be wrong? (I'd like to remove the second parameter from #dispatch_event.) #!/usr/local/bin/ruby require 'libs/binding_of_caller' module EventTarget def add_event_listener( name, callback ) callbacks = ((@registered_events ||= {})[ name.to_s ] ||= []); callbacks.delete( callback ) callbacks << callback end def dispatch_event( evt, source ) callbacks = (@registered_events ||= {})[ evt.name ]; return unless callbacks #evt.source = Binding.of_caller{ |b| eval("self", b) } evt.source = source callbacks.each{ |m| m.call( evt ) } end end class Event attr_accessor :name, :source, :change def initialize( name, change=nil ) @name = name.to_s @change = change end end class HTMLInput include EventTarget attr_reader :value def value=( v ) @value = v evt = Event.new( 'change', v ) dispatch_event( evt, self ) end end inp = HTMLInput.new inp.add_event_listener( 'change', Proc.new{ |e| puts "#{e.source} just changed." } ) inp.add_event_listener( 'change', Proc.new{ |e| puts "The new value is #{e.change}." } ) inp.value = 12 #=> # just changed. #=> The new value is 12 -- (-, /\ \/ / /\/