From: Jacob Fugal Date: 2005-07-19T23:18:45+09:00 Subject: Re: ] Re: Ruby has ruined my Java (was Re: Ruby has ruined my C++) On 7/18/05, Daniel Amelang wrote: > So, tell my why you prefer the on_event( :event_type ) syntax? > > I prefer the when_pushed syntax because of the readablity and > abstraction of events altogether. 'button when pushed do this' feels > very natural. But maybe it feels very unnatural for others. 'button on > event push' is OK with me, it's the fxRuby way after all. > > The when_pushed method would actually (via the magic of method missing > possibly) translate to something like register_handler (:push, block) > under the hood. I don't know, it's just preference. :) Your syntax is a good alternative. But I'll take a stab at explaining my preference anyway... I think the main difference is the conciseness of the grammar style, and an easier reflection between event handling and event generation. For one thing, the 'when_pushed' variant would need a translation in method_missing to turn 'pushed' into :push. The 'on_*' route doesn't necessarily preclude method_missing abstraction either: module EventListener def register_handler( event_name, &action ) @actions ||= {} @actions[event_name] ||= [] @actions[event_name] << action end def handle_event( event_name ) if @actions[event_name] @actions[event_name].each { |action| action[self] } end end def method_missing( symbol, *args, &block ) if /^on_/.match( symbol ) self.register_handler( symbol.to_s.gsub(/^on_/, '').to_sym, *args ) &block else self.handle_event( symbol ) end end end class Button include EventListener end button = Button.new button.on_push do |b| puts "Don't push my buttons!" end button.push