[Tutor] event-based programming

Sean 'Shaleh' Perry shalehperry@attbi.com
Fri, 12 Jul 2002 12:22:01 -0700 (PDT)


On 12-Jul-2002 Erik Price wrote:
> I was wondering if one (or more) of the helpful geniuses on this list 
> could help me understand how event-based programming works.  This is 
> something that I have seen in a Java program called RoboCode and also in 
> JavaScript-enabled web browsers, which trigger event handlers written in 
> JavaScript embedded into an HTML documents, and I'm sure that it can be 
> done with a language like Python.  But what I don't understand is how 
> the program knows to "watch" for the event.
> 
> Does the event have to "target" the event handler with a message, or 
> does the simple act of an "event" being triggered cause the event 
> handler to execute?  In other words, does the event handler watch some 
> specific code for an event to happen, or does the event have to be sent 
> to the event handler?  And how does one write code that "watches" for 
> events in this fashion, regardless of whether it is targetted or not -- 
> does that mean that event-based code must be written like a daemon, 
> constantly running and waiting for messages?
> 
> I'm hoping someone can give me a very high-level, theoretical 
> explanation of how this works.
> 

In general event systems work on a "subscribe/notify" basis.  The application
that wants to hear events tells the event source that is is interested in
events.  When an event occurs the source then sends the event to each subscriber
application.  You may also see this referred to as listen/send.

GUI applications also use this style of communication.

In psuedo code.

event source:

accept_subscribe message, input is who and what:
  store in listeners who, what

on event generate:
  for each who in listeners
    if what matches event
      send event to who

the subscribe application:

send_subscribe, supply identity and interest

receive event:
  call handler for event

This can be seen as any number of real world events.  Consider the home that
subscribes to news via the morning paper.

Home sends subscription notification to company
when newspaper is ready it is shipped to the Home
when the Home has time to read the paper the news is accepted

Add to this something like your monthly fee for reading the paper.  If you stop
paying the paper stops coming.  Many systems will have the event source check
that the listener is still there and stop sending events or the burden is on
the listener to periodically resubscribe.

Hope this helps.