From: Massimiliano Mirra Date: 2002-02-02T07:34:00+09:00 Subject: Re: [GUI] Signal/slot pattern in ruby On Fri, Feb 01, 2002 at 11:54:49PM +0900, Niklas Frykholm wrote: > I have been thinking a bit of how I would want message passing to work > in an ideal ruby GUI. > > I think the signal/slot mechanism in Qt is the most elegant basic > mechanism. (The other options are AFAIK: callbacks, observers and > subclassing.) In a ruby GUI, signals and slots should be ordinary ruby > functions. It should also be possible to use Proc's as slots. Like > this: The following code I wrote a while ago when needing something uniform with GTK is very similar. It supports more than one event handler for a given event like GTK, but doesn't support disconnecting (didn't need that). module Signal def signal_connect(sigstr, &block) @handlers ||= {} unless @handlers[sigstr] array = [] def array.call(*args) each {|handler| handler.call(*args)} end @handlers[sigstr] = array end @handlers[sigstr].push block end def sighandle(sigstr, *args) if @handlers @handlers[sigstr].call(*args) unless @handlers[sigstr].nil? end end end if __FILE__ == $0 class Test include Signal def foo sighandle("foo_event", 2) end end t = Test.new t.signal_connect('foo_event') {puts "event called"} t.signal_connect('foo_event') {|param| puts "second handler, using the passed param: #{param}"} # do whatever you want here t.foo end Massimiliano