Event Handler CS Thinking Example 4
Follow the full solution, then compare it with the other examples linked below.
Example 4
hardExplain the problem of attaching an event handler inside a loop: FOR i = 0 TO 4: WHEN buttons[i].clicked: OUTPUT i. If you click button 3 after the loop finishes, what might be output and why?
Solution
- 1 Step 1: In many languages, the handler captures a reference to the variable i, not its current value. After the loop, i = 5.
- 2 Step 2: Clicking any button would output 5 (the final value of i), not the button's index. This is the 'closure over loop variable' bug.
- 3 Step 3: Fix: capture the value at each iteration, e.g., create a local copy: SET index = i. WHEN buttons[index].clicked: OUTPUT index. Each handler now has its own copy.
Answer
All buttons would output 5 (the final loop value). Fix by capturing the loop variable's value in a local variable for each iteration.
The closure-over-loop-variable problem is a classic bug in event-driven programming. Understanding variable capture in closures is essential for writing correct event handlers.
About Event Handler
A function that is automatically called when a specific event occurs, such as a button click, key press, or timer tick. The handler is registered (attached) to an event source once, and then the system invokes it every time that event fires.
Learn more about Event Handler โMore Event Handler Examples
Example 1 easy
In a web page, a button has this event handler: WHEN button.clicked: OUTPUT 'Button was clicked!'. E
Example 2 mediumWrite pseudocode for a simple calculator with buttons for digits 0-9 and an '=' button. How would yo
Example 3 mediumA form has a text input and a submit button. Write pseudocode for event handlers that: (1) validate