Table of Contents

    Event-driven Programming

    Programming Mastery

    Event-driven Programming

    Learn how programs can wait for events and respond automatically when users click, type, submit forms, receive messages, or when system changes occur.

    What is Event-driven Programming?

    Event-driven Programming is a programming paradigm where the flow of a program is controlled by events.

    An event is something that happens in a program or system. For example, a user clicks a button, presses a key, submits a form, receives a message, a timer finishes, or a file download completes.

    Event-driven programming means the program waits for events and runs specific code when those events occur.

    In traditional programming, the program usually runs step by step from top to bottom. But in event-driven programming, the program waits and reacts when something happens.

    Traditional Flow:
    Step 1 → Step 2 → Step 3 → End
    
    Event-driven Flow:
    Wait for event → Event happens → Run handler → Wait again

    Easy Real-Life Example

    Event-driven Programming as a Doorbell

    Imagine you are waiting for a guest. You do not continuously open the door every few seconds to check whether the guest has arrived. Instead, you wait for the doorbell. When the doorbell rings, you open the door.

    In this example:

    Doorbell rings → Event
    You hear the doorbell → Event listener
    You open the door → Event handler

    Similarly, in programming, the system waits for an event. When the event happens, a specific function runs.

    Why is Event-driven Programming Needed?

    Event-driven programming is needed because modern applications are interactive. Users can click buttons, type text, drag items, open menus, submit forms, upload files, or receive notifications at any time.

    The program cannot always predict what the user will do next. So instead of following only one fixed sequence, it waits for events and responds accordingly.

    Event-driven Programming is Used For

    • Graphical user interface applications.
    • Web applications.
    • Mobile apps.
    • Games.
    • Form validation.
    • Button click actions.
    • Keyboard shortcuts.
    • Mouse movement and drag-and-drop features.
    • Real-time notifications.
    • Chat applications.
    • IoT and sensor-based systems.
    • Asynchronous systems and message-based applications.
    Key Idea: Event-driven programming is useful when a program must react to actions or changes that can happen at any time.

    Important Terms in Event-driven Programming

    Term Meaning Example
    Event An action or occurrence detected by the program. Button click, key press, timer finish.
    Event Source The object or component that creates the event. Button, input box, sensor.
    Event Listener A mechanism that waits for a specific event. Listening for button click.
    Event Handler A function that runs when an event occurs. Function that runs after clicking submit.
    Callback A function passed to be executed later when an event happens. onClickFunction
    Event Loop A loop that waits for events and sends them to handlers. GUI or browser event loop.
    Asynchronous Tasks can happen without blocking the entire program. Download file while UI remains responsive.

    What is an Event?

    An event is any meaningful action or occurrence that a program can detect.

    Events can come from users, the system, network, hardware, or another program.

    Common Types of Events

    • Mouse Events: click, double-click, mouse move, drag.
    • Keyboard Events: key press, key release, typing.
    • Form Events: submit, reset, input change.
    • Window Events: page load, resize, close.
    • Timer Events: countdown finished, scheduled action.
    • Network Events: message received, request completed.
    • System Events: file created, sensor alert, state changed.
    Examples of events:
    
    User clicks Login button
    User types in search box
    Timer reaches zero
    Message arrives from server
    File upload completes
    Sensor detects motion

    What is an Event Source?

    An event source is the object or component that produces an event.

    For example, if a user clicks a button, the button is the event source.

    Button → creates click event
    Text box → creates input event
    Timer → creates timeout event
    Sensor → creates alert event

    What is an Event Listener?

    An event listener waits for a particular event to happen.

    It is like saying:

    "When this event happens, run this function."

    Example idea:

    Listen for button click
    When button is clicked
    Run login function

    What is an Event Handler?

    An event handler is the function or block of code that runs when an event occurs.

    If the event is button clicked, the event handler may validate a form, display a message, save data, or open a new page.

    Simple Event Handler Pseudocode

    FUNCTION handleLoginButtonClick()
        DISPLAY "Login button clicked"
    END FUNCTION
    
    WHEN loginButton IS CLICKED
        CALL handleLoginButtonClick()
    END WHEN

    Basic Event-driven Program Flow

    The basic flow of an event-driven program looks like this:

    1. Program starts
    2. Program registers event listeners
    3. Program waits for events
    4. Event occurs
    5. Event handler runs
    6. Program waits for the next event
    Important: In event-driven programming, the program does not always run in a fixed order. The order depends on which event happens first.

    Event Loop

    The event loop is a mechanism that continuously checks for events and sends them to the correct event handlers.

    The event loop keeps the program alive and responsive.

    Event Loop Pseudocode

    WHILE program is running
        WAIT for event
    
        IF event occurs THEN
            FIND matching event handler
            RUN event handler
        END IF
    END WHILE

    In many programming environments, the event loop is managed by the framework, browser, operating system, or runtime. Beginners usually write the event handlers, while the environment manages the loop.

    Callback Function

    A callback is a function that is passed to another part of the program and called later when something happens.

    In event-driven programming, callbacks are commonly used as event handlers.

    FUNCTION showMessage()
        DISPLAY "Button was clicked"
    END FUNCTION
    
    REGISTER showMessage AS callback FOR button click

    Here, showMessage is not called immediately. It is called later when the button click event occurs.

    Example 1: Button Click Event

    /*
    This example shows a button click event.
    */
    
    FUNCTION handleButtonClick()
        DISPLAY "You clicked the button"
    END FUNCTION
    
    ENTRY POINT
        REGISTER handleButtonClick FOR button click event
    
        WAIT FOR EVENTS
    END ENTRY POINT

    Expected Output After Click

    You clicked the button

    Example 2: Text Input Event

    /*
    This example responds when a user types something.
    */
    
    FUNCTION handleTextChange(newText)
        DISPLAY "User typed: " + newText
    END FUNCTION
    
    ENTRY POINT
        REGISTER handleTextChange FOR text input change event
    
        WAIT FOR EVENTS
    END ENTRY POINT

    Example Output

    User typed: Programming

    Example 3: Form Submit Event

    /*
    This example validates a form when the user submits it.
    */
    
    FUNCTION handleFormSubmit(username, password)
        IF username is empty OR password is empty THEN
            DISPLAY "Username and password are required"
        ELSE
            DISPLAY "Form submitted successfully"
        END IF
    END FUNCTION
    
    ENTRY POINT
        REGISTER handleFormSubmit FOR form submit event
    
        WAIT FOR EVENTS
    END ENTRY POINT

    Example Output

    Form submitted successfully

    Example 4: Timer Event

    /*
    This example runs code when a timer finishes.
    */
    
    FUNCTION handleTimerEnd()
        DISPLAY "Time is up"
    END FUNCTION
    
    ENTRY POINT
        START timer for 10 seconds
        REGISTER handleTimerEnd FOR timer end event
    
        WAIT FOR EVENTS
    END ENTRY POINT

    Expected Output After Timer Ends

    Time is up

    Example 5: Notification Event

    /*
    This example sends notification when a product price drops.
    */
    
    FUNCTION handlePriceDrop(productName, oldPrice, newPrice)
        DISPLAY "Price dropped for " + productName
        DISPLAY "Old Price: " + oldPrice
        DISPLAY "New Price: " + newPrice
    END FUNCTION
    
    ENTRY POINT
        REGISTER handlePriceDrop FOR price drop event
    
        WAIT FOR EVENTS
    END ENTRY POINT

    Example Output

    Price dropped for Keyboard
    Old Price: 700
    New Price: 550

    Event-driven Architecture Idea

    Event-driven programming can also be used in larger systems where different components communicate using events.

    Order Placed Event
            ↓
    Update Inventory
            ↓
    Send Confirmation Email
            ↓
    Notify Delivery Team

    In this design, one event can trigger multiple actions. The system becomes flexible because different parts can react to the same event.

    Event-driven vs Sequential Programming

    Feature Sequential Programming Event-driven Programming
    Flow Runs step by step in a fixed order. Runs based on events.
    Control Program controls the flow. Events control the flow.
    Best For Simple calculations and scripts. Interactive and responsive applications.
    Example Calculate total marks line by line. Run logic when a button is clicked.
    Execution Order Predictable and fixed. Depends on event occurrence.

    Event-driven Programming vs Functional Programming

    Event-driven programming and functional programming solve different problems.

    Feature Functional Programming Event-driven Programming
    Main Focus Pure functions and immutable data. Events and responses.
    Trigger Function calls and data transformations. User actions, messages, timers, system changes.
    Common Use Data processing and predictable logic. Interactive applications and asynchronous systems.
    Can They Work Together? Yes, event handlers can use pure functions internally. Yes, events can trigger functional transformations.

    Advantages of Event-driven Programming

    Benefits

    • Makes applications responsive.
    • Works well for user interfaces.
    • Allows programs to react to user actions.
    • Supports asynchronous behavior.
    • Helps avoid blocking the whole application.
    • Makes it easier to handle multiple types of actions.
    • Improves modularity by separating event handling logic.
    • Works well in real-time systems and notification systems.
    • Useful for web, mobile, desktop, games, and IoT applications.

    Limitations of Event-driven Programming

    Challenges

    • Execution order can be harder to follow.
    • Debugging may be more difficult because events happen asynchronously.
    • Too many event handlers can make code confusing.
    • Incorrect event handling can cause repeated or unexpected actions.
    • Shared data must be managed carefully.
    • Complex event chains can become difficult to understand.
    • Beginners may find callbacks and event loops confusing at first.

    Event-driven Program Structure

    A simple event-driven program usually has the following parts:

    1. Define event handlers
    2. Register event listeners
    3. Start application
    4. Wait for events
    5. Execute matching handlers
    6. Repeat

    General Template

    FUNCTION eventHandler(eventData)
        PROCESS eventData
    END FUNCTION
    
    ENTRY POINT
        REGISTER eventHandler FOR eventType
    
        START event loop
    END ENTRY POINT

    Real-World Example: Online Shopping Cart

    In an online shopping website, many actions are event-driven.

    Shopping Cart Events

    • User clicks Add to Cart.
    • User removes an item.
    • User changes item quantity.
    • User applies a coupon.
    • User clicks checkout.
    • Payment success event occurs.
    • Order confirmation notification is sent.
    EVENT: Add to Cart clicked
    HANDLER:
        Add product to cart
        Update total price
        Display cart count

    Real-World Example: Game Controls

    Games are highly event-driven. The game reacts to keyboard, mouse, controller, timer, collision, and score events.

    EVENT: Player presses Space key
    HANDLER:
        Make player jump
    
    EVENT: Enemy touches player
    HANDLER:
        Reduce player health
    
    EVENT: Timer reaches zero
    HANDLER:
        End game

    Best Practices for Event-driven Programming

    Recommended Practices

    • Keep event handlers small and focused.
    • Use clear names for events and handlers.
    • Do not put too much logic directly inside one event handler.
    • Separate user interface logic from business logic.
    • Validate event data before using it.
    • Avoid registering duplicate listeners accidentally.
    • Handle errors inside event handlers.
    • Use comments for complex event flows.
    • Keep event names meaningful.
    • Test different event sequences, not just one fixed flow.

    Common Beginner Mistakes

    Mistakes

    • Thinking event-driven programs always run from top to bottom.
    • Calling an event handler immediately instead of registering it.
    • Putting all logic inside one large event handler.
    • Forgetting to validate user input inside event handlers.
    • Registering the same event listener multiple times by mistake.
    • Not handling missing or invalid event data.
    • Assuming events always happen in the same order.
    • Creating event chains that are hard to trace.

    Better Habits

    • Understand which event triggers which handler.
    • Keep handlers short and readable.
    • Use helper functions for repeated logic.
    • Use meaningful event names.
    • Test multiple user action sequences.
    • Keep shared data changes controlled.
    • Separate event handling from core calculation logic.
    • Document important event flows.

    Prerequisites Before Learning Event-driven Programming

    Students should understand the following topics before learning event-driven programming:

    Required Knowledge

    • Variables and data types.
    • Input and output.
    • Operators.
    • Conditions.
    • Loops.
    • Functions and methods.
    • Lists and maps/dictionaries.
    • Basic user input validation.
    • Basic idea of callbacks or function references.

    Trace Table Example: Button Click Event

    Let us trace a simple button click event.

    User clicks Submit button
    handleSubmit() function runs
    Form data is validated
    Message is displayed
    Step Action Program Response
    1 User clicks button Click event is created
    2 Event listener detects click Matching handler is found
    3 Handler runs Form data is checked
    4 Validation completes Success or error message is displayed

    Practice Activity: Identify Events and Handlers

    Study the following situations and identify the event and the event handler.

    1. User clicks Login button.
    2. User types in a search box.
    3. Timer reaches zero.
    4. New chat message arrives.
    5. User submits registration form.

    Sample Answers

    1. Event: Login button click
       Handler: Validate login details
    
    2. Event: Search input change
       Handler: Show matching search results
    
    3. Event: Timer finished
       Handler: Display "Time is up"
    
    4. Event: Message received
       Handler: Show message notification
    
    5. Event: Registration form submit
       Handler: Validate and save user data

    Mini Quiz

    1

    What is event-driven programming?

    Event-driven programming is a programming paradigm where the program waits for events and responds by running specific event handlers.

    2

    What is an event?

    An event is an action or occurrence detected by the program, such as a button click, key press, timer completion, or message arrival.

    3

    What is an event handler?

    An event handler is a function that runs in response to a specific event.

    4

    What is an event listener?

    An event listener waits for a specific event and connects that event to the correct handler.

    5

    Why is event-driven programming useful?

    It is useful because it helps create responsive applications that react to user actions, system changes, messages, timers, and real-time events.

    Interview Questions on Event-driven Programming

    1

    Define event-driven programming.

    Event-driven programming is a style of programming where program execution is controlled by events and the program responds using event handlers.

    2

    What is the difference between an event and an event handler?

    An event is something that happens, while an event handler is the function that runs when that event happens.

    3

    What is an event loop?

    An event loop is a mechanism that waits for events and dispatches them to the correct event handlers.

    4

    Where is event-driven programming commonly used?

    It is commonly used in graphical user interfaces, web applications, mobile apps, games, notification systems, and asynchronous applications.

    5

    Why can event-driven programs be harder to debug?

    They can be harder to debug because events may occur asynchronously and not always in a fixed order.

    Quick Summary

    Concept Meaning
    Event-driven Programming Programming style where events control the program flow.
    Event An action or occurrence detected by the program.
    Event Source The component that creates an event.
    Event Listener Waits for a specific event.
    Event Handler Runs when the event occurs.
    Callback A function executed later in response to an event.
    Event Loop Continuously waits for and dispatches events.
    Best Use Interactive, responsive, asynchronous, and real-time applications.

    Final Takeaway

    Event-driven programming is a powerful paradigm used to build interactive and responsive applications. Instead of running only in a fixed sequence, an event-driven program waits for actions or changes and responds through event handlers. In the Programming Mastery Course, students should understand event-driven programming as the foundation of user interfaces, web interactions, games, notification systems, asynchronous applications, and real-time software.