Version 4 (modified by hopscc, 13 years ago) |
---|
Listen
Connect an event to some particular handling code by giving an event
handler (method reference) for a particular Event instance.
When the event is raised (or fired) the method (event handler) is
invoked with the args given to raise the event.
An event is specified as a name typed to a sig (signature/delegate).
Any method given as an eventhandler/listener must conform to the same sig.
For disconnecting an event from its handling code see Ignore.
For firing an event see Raise.
Grammar
listen <event>, <method-reference>
Examples
use System.Windows.Forms ... button = Button(parent=p, autoSize=true, text='One', tag=1) listen button.click, ref .clickHandler ... def clickHandler(source as Object, args as EventArgs) pass
Full example showing sig and event declaration and method to raise the event.
# delegate for ActionEvent <eventName>EventHandler sig ActionEventHandler(sender as Object, args as EventArgs) class Generator # event declaration for an event called Action # event <eventName>Event as <sigName> (<eventName>EventHandler) event actionEvent as ActionEventHandler # (protected) method to raise/fire the event for this class # {on,fire}<eventName>Event def _onActionEvent(args as EventArgs) # fireActionEvent raise .actionEvent, args class Listener # the event handler method do<eventName> def doAction(source as Object, args as EventArgs) print 'Event received from [source]' ... def driver g = Generator() l = Listener() #tie the generator event to the Listener method listen g.actionEvent, ref l.doAction
# The event handler method can also be declared using a closure if that's desirable listen g.actionEvent, do(source as Object, args as EventArgs) print 'Event received from [source]' # Heres an example wrt GTK# declaring an eventhandler for an Application exit button # the indented code on the lines following the do( is the closure code listen button.clicked, do(sender, args as EventArgs) print 'Quitting' Application.quit
Notes
The event handler method must be a reference to a method not a
method invocation.
In practice this means that most listen statements will have their second
argument as a method name prefixed with ref.
You need the ref keyword to specify a reference to a named method so that it is not invoked.
A closure (using do) is itself referring to code (rather than invoking it) so
you never need both ref and do at the same time.