An introduction to Event-Driven Programming

Event-driven programming or Event-based programming refers to a computer programming technique that involves controlling the flow of a program by receiving signals (also called messages or events) from an outside source. The source of the message can be anything from another program, a thread, or it could be generated from within the program. There are two necessary data structures for the construction of an event-driven system: an event listener and an event handler.

An event listener will store messages that are passed to it from an outside source. This is usually implemented as a queue or stack. Messages are stored for later dispatching by the event handler. Observe the following diagram.

Event Driven Diagram

Messages A, B, and C get passed to the event listener which will then be retrieved by the event handler. These messages could be generated from a variety of sources and generated at different time intervals. It is important to note that until the event handler processes the messages, the event listener will store them.

Event Driven programming is heavily used in Graphical User Interfaces (GUIs). Imagine what happens when you move the mouse and press the left mouse button. First, a mouse move message would be sent to the window that has the focus. Maybe the window will want to know the new x and y coordinate of the mouse position. Second, a mouse click message will be sent to the window. If the mouse cursor is over a button then the left click would trigger another event that would get sent to the event listener. Imagine writing a program that had to check for each of the possible actions a user could perform in your program. You would waste CPU cycles checking for events that did not happen. Event driven programming solves this problem.

Event driven programming is a different way to think about the flow of your program. Usually when one sets out to learn programming, he or she thinks of the flow of the program as a linear progression from beginning to end. Using event driven programming, you can think in terms of events that happen to your program.

Back to Main Page