| 1 | = Listen = |
| 2 | |
| 3 | Connect an event to some particular handling code by giving an event |
| 4 | handler (method reference) for a particular Event instance.[[BR]] |
| 5 | When the event is raised (or fired) the method (event handler) is |
| 6 | invoked with the args given to raise the event. |
| 7 | |
| 8 | An event is specified as a name typed to a sig (signature/delegate).[[BR]] |
| 9 | Any method given as an eventhandler/listener must conform to the same sig. |
| 10 | |
| 11 | For disconnecting an event from its handling code see [wiki:Ignore].[[BR]] |
| 12 | For firing an event see [wiki:Raise]. |
| 13 | |
| 14 | == Grammar == |
| 15 | {{{ |
| 16 | listen <event>, <method-reference> |
| 17 | }}} |
| 18 | |
| 19 | |
| 20 | == Examples == |
| 21 | {{{ |
| 22 | use System.Windows.Forms |
| 23 | |
| 24 | ... |
| 25 | button = Button(parent=p, autoSize=true, text='One', tag=1) |
| 26 | listen button.click, ref .clickHandler |
| 27 | ... |
| 28 | def clickHandler(source as Object, args as EventArgs) |
| 29 | pass |
| 30 | }}} |
| 31 | |
| 32 | Full example showing sig and event declaration and method to raise the event. |
| 33 | {{{ |
| 34 | |
| 35 | # delegate for ActionEvent <eventName>EventHandler |
| 36 | sig ActionEventHandler(sender as Object, args as EventArgs) |
| 37 | |
| 38 | class Generator |
| 39 | # event declaration for an event called Action |
| 40 | # event <eventName>Event as <sigName> (<eventName>EventHandler) |
| 41 | event actionEvent as ActionEventHandler |
| 42 | |
| 43 | # (protected) method to raise/fire the event for this class |
| 44 | # {on,fire}<eventName>Event |
| 45 | def _onActionEvent(args as EventArgs) # fireActionEvent |
| 46 | raise .actionEvent, args |
| 47 | |
| 48 | class Listener |
| 49 | # the event handler method do<eventName> |
| 50 | def doAction(source as Object, args as EventArgs) |
| 51 | print 'Event received from [source]' |
| 52 | |
| 53 | ... |
| 54 | def driver |
| 55 | g = Generator() |
| 56 | l = Listener() |
| 57 | |
| 58 | #tie the generator event to the Listener method |
| 59 | listen g.actionEvent, ref l.doAction |
| 60 | }}} |
| 61 | |
| 62 | {{{ |
| 63 | # Todo example using closure/anonymous method |
| 64 | }}} |
| 65 | |
| 66 | == Notes == |
| 67 | |
| 68 | The event handler method must be a reference to a method not a |
| 69 | method invocation.[[BR]] |
| 70 | In practice this means that most listen statements will have their second |
| 71 | argument as a method name prefixed with '''ref'''. |