Cos214 (Computer Programming II, Event-Driven Programming)
Cos214 (Computer Programming II, Event-Driven Programming)
Definition
Event-driven programming is a programming paradigm where the flow of execution is
determined by events such as:
Key Characteristics
• Asynchronous:
Code execution is driven by events rather than a predefined sequence.
• Reactive:
Functions (also called event handlers) are executed only when an event occurs.
• Non-blocking:
The system remains responsive, handling other operations while waiting for events.
Common Applications
• Graphical User Interfaces (GUIs)
→ E.g., button clicks, menu selections, drag-and-drop.
• Game Development
→ E.g., keyboard inputs, collisions, in-game timers.
Definition
Event-handling methods are functions (also known as event handlers) that execute in response
to specific events triggered by the user or system.
import tkinter as tk
root = tk.Tk()
button = tk.Button(root, text="Click Me") # Bind the left mouse button click event to
the handler
button.bind("<Button-1>", on_button_click)
button.pack()
root.mainloop()
• Types of Events:
▪ Window resize
Definition
Event propagation is the process by which an event moves through the UI element hierarchy
(DOM tree) after being triggered. It determines when and where event handlers are executed.
1. Capturing Phase
o The event travels from the top of the DOM (e.g., window) down to the target
element.
2. Target Phase
o The event reaches the actual target element that was interacted with.
3. Bubbling Phase
o The event bubbles back up from the target to its ancestors.
document.getElementById("parent").addEventListener(
"click",
"click",
Why It Matters
• Control Flow
Decide where to handle an event — at the target or one of its ancestors.
• Event Management
Use event.stopPropagation() to prevent the event from continuing up or down the tree.
• Performance Optimization
Avoid unnecessary event handling at higher levels of the UI hierarchy.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<style>
padding: 20px;
margin: 10px;
}
#grandparent { background-color: #fce4ec; }
#parent { background-color: #f8bbd0; }
</style>
</head>
<body>
<div id="grandparent">
Grandparent
<div id="parent">
Parent
<div id="child">
Child
</div>
</div>
</div>
<script>
</script>
</body>
</html>
The Challenge
try:
risky_operation()
except Exception as e:
print(f"Error: {e}") # Graceful fallback
• In Browsers:
};
• In Python (tkinter):
Override the report_callback_exception method in the Tk class to catch unhandled
exceptions in the GUI.
GUI-Specific Concerns
Thread Safety
• GUIs usually run on a single main thread.
• Blocking operations (e.g., file downloads, database access) should be offloaded using:
o Async callbacks
• Avoid modifying shared data across multiple event handlers unless properly
synchronized.
• Use flags, queues, or locks to manage state transitions predictably.
Applications in GUI Programming
These events allow the interface to respond dynamically to user actions, improving usability and
interactivity.
o tkinter (Python)
• Web:
try {
});
Highlights:
• addEventListener: Binds the event to the element.
Core Insights
2. Event Handlers are functions tied to specific events (e.g., onClick, onKeyPress) and are
executed when those events occur.
3. Event Propagation describes how events traverse the UI component tree through:
o Capturing Phase (top-down)
4. Robust Exception Handling is essential for stability in GUI applications. Errors in one
handler should not crash the entire system.
5. GUI Applications (both desktop and web) fundamentally rely on events for
responsiveness and interactivity.
• Observer Pattern
A foundational design pattern in which subscribers (observers) automatically receive
updates when an observable changes state. Common in GUI toolkits and MVC
frameworks.
• Reactive Programming
A declarative paradigm for working with asynchronous data streams. Popular libraries
include:
o RxJS (JavaScript)
o RxPY (Python)
o Reactor (Java)
It builds on the observer pattern and allows composition of events using operators like map,
filter, and merge.