Event Handler CS Thinking Example 2
Follow the full solution, then compare it with the other examples linked below.
Example 2
mediumWrite pseudocode for a simple calculator with buttons for digits 0-9 and an '=' button. How would you use event handlers to build this?
Solution
- 1 Step 1: SET display = ''. FOR each digit button (0-9): WHEN digitButton.clicked: display = display + digitButton.value.
- 2 Step 2: WHEN equalsButton.clicked: result = EVALUATE(display). display = STRING(result).
- 3 Step 3: Each button has its own event handler. The digit handlers append to the display string; the equals handler evaluates the expression. Multiple handlers work together to create the full calculator behaviour.
Answer
Each button has an event handler: digit buttons append their value to the display, equals button evaluates the expression.
Breaking interactive applications into event handlers is a form of decomposition. Each handler is simple, but together they create complex behaviour.
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 3 mediumA form has a text input and a submit button. Write pseudocode for event handlers that: (1) validate
Example 4 hardExplain the problem of attaching an event handler inside a loop: FOR i = 0 TO 4: WHEN buttons[i].cli