Computer science
Events & reactions
Programs wait for clicks, keys and messages and react to them in a flash.
What you need first
You tap an icon and the app opens. You press a key and a letter appears. Your phone buzzes because a message arrives. Behind all of this is the same idea: the program waits for an event and reacts to it. Without this principle every app would just be a rigid movie, with it the app becomes something that listens to you.
What is an event?
An event is something that happens and that a program can react to: a click, a key press, an incoming message, a timer that runs out, or a sensor value that changes. For each event the program can have a rule: if this event occurs, then run this reaction. Such a rule is also called an event handler. It has the same if-then shape as a condition, only it is not the program that decides when its turn comes, but the event.
Apps are collections of rules
You can picture a whole app as a collection of such event rules: when the start button is pressed, start the game. When a message arrives, show a notification. When the battery is almost empty, dim the screen. Most of the time the app does nothing at all, it just waits. Only when an event occurs does the matching rule run.
Different from step by step
So far you knew programs that work through a fixed list of steps from top to bottom, like a recipe. Event driven programs are different: it is not fixed what happens next, because you decide that with your clicks and inputs. The order of the reactions depends on which events occur in which order.
Exercises
0 of 6 solvedTime to try it yourself. You can't break anything, every attempt counts.
What is an event in a program?
A rule says: when the button is clicked, then play a sound. What happens as long as nobody clicks?
An app has 3 buttons. Each button has 2 event rules: one for a short tap and one for a long press. How many event rules is that in total?
Match each event to the reaction an app shows for it.
Each click on a button raises a score counter by 5. It starts at 0. How many points does it show after 7 clicks?
Most of the time an event driven app does nothing at all, it just ….
Where this leads