OOPs4Humans

Event-Driven Programming

Don't call us, we'll call you.

Event-Driven Programming

Analogy: concept

Event-Driven Programming is like a Radio Station:

  • The Emitter (Station): Broadcasts a signal (Event).
  • The Listener (Radio): Tunes in to specific frequencies.
  • The Handler: The song or news that plays when the signal is received.

The Station doesn't know WHO is listening. It just broadcasts.

The Signal Tower

Emit different signals and see who reacts. Notice that some listeners care about multiple events, while others ignore them.

Event-Driven Architecture (Signal Tower)

Fire Station
Listens to: FIRE
Idle
Shopper
Listens to: SALE
Idle
News Anchor
Listens to: NEWS, FIRE
Idle

Key Concepts

  1. Event: Something that happens (Click, Keypress, Data Loaded).
  2. Emitter: The object that announces the event.
  3. Listener (Observer): The object waiting for the event.
  4. Decoupling: The Emitter doesn't need to know the Listener's details.

The Code

Java Example
Switch language in Navbar
// 1. Define the Listener Interface
interface AlarmListener {
    void onAlarm();
}

// 2. The Emitter
class FireAlarm {
    List<AlarmListener> listeners = new ArrayList<>();
    void addListener(AlarmListener l) { listeners.add(l); }
    void trigger() {
        for (AlarmListener l : listeners) l.onAlarm(); // Notify!
    }
}

// 3. The Listener
class FireStation implements AlarmListener {
    public void onAlarm() { System.out.println("Trucks deployed!"); }
}
Up Next
Namespaces