- Home
- /
- Computational Thinking
- /
- Programming Fundamentals
- /
- Event Handler
Event Handler
Also known as: event listener, callback
Grade 6-8
View on concept mapA function that is automatically called when a specific event occurs, such as a button click, key press, or timer tick. All interactive software β websites, apps, games β uses event handlers.
Definition
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.
π‘ Intuition
An event handler is like setting a trap β you define what should happen, then wait. When the event fires, your code runs automatically.
π― Core Idea
Event-driven programming reverses the usual flow β instead of your code deciding when to run, external events trigger it.
Example
π Why It Matters
All interactive software β websites, apps, games β uses event handlers. They are how programs respond to user actions in real time. Without event handlers, programs could not react to clicks, keypresses, network responses, or any external stimulus.
π Hint When Stuck
When creating an event handler, write the function that should run when the event occurs, then register it with the event source (e.g., button.onClick(myHandler)). The handler function does not run at registration timeβit waits until the event actually fires.
Formal View
Related Concepts
π§ Common Stuck Point
An event handler is registered (set up) once but can fire many times. Setting it up doesn't run it immediately.
β οΈ Common Mistakes
- Calling the function immediately instead of passing it as a reference (button.onClick(myHandler()) runs it now; button.onClick(myHandler) registers it)
- Registering the same handler multiple times, causing it to fire more than once per event
- Writing slow event handlers that block the main thread and make the interface freeze
Frequently Asked Questions
What is Event Handler in CS Thinking?
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.
When do you use Event Handler?
When creating an event handler, write the function that should run when the event occurs, then register it with the event source (e.g., button.onClick(myHandler)). The handler function does not run at registration timeβit waits until the event actually fires.
What do students usually get wrong about Event Handler?
An event handler is registered (set up) once but can fire many times. Setting it up doesn't run it immediately.
Prerequisites
How Event Handler Connects to Other Ideas
To understand event handler, you should first be comfortable with event and function programming.