3.2. Theory of Signals and Callbacks

In GTK version 2.0, the signal system has been moved from GTK to GLib. We're not going to go into any detail about the extensions which the GLib 2.0 signal system has relative to the GTK 1.2 signal.

Before we look in detail at helloworld.rb, we'll discuss signals and callbacks. GTK is an event driven toolkit (and thus Ruby-GNOME2 by default), which means it sleeps in Gtk.main until an event occurs and control is passed to the appropriate method.

This passing of control is done using the idea of "signals". (Note: These signals are not the same as UNIX system signals, and are not implemented using them, although the terminology is almost identical.) When an event occurs, such as the press of a mouse button, the appropriate signal will be "emitted" by the widget that was pressed. This is how GTK does most if it's useful work. There are signals that all widgets inherit, such as "destroy", and there are signals that are widget specific, such as "toggled" on a toggle button.

To make a button perform an action, we set up a signal handler to catch these signals and call the appropriate method. This is done by using a method such as:

GLib::Instantiatable#signal_connect( "signal_to_catch" ) { |widget| callback_method }

The first and only argument is the name of the signal you wish to catch. Within the code block, you can catch the widget that emitted the signal, |widget|, and then you make a call to callback_method. You can pass data and/or the widget to the callback method if you so desire.

The method named in the code block, callback_method is called a "callback method", and should generally be of the form:

callback_method( widget )

Where the first and only argument is the widget that emitted the signal. Please note that the above form for a signal callback is only a very general guide, as some widget specific signals generate different calling parameters.


Prev Next