Skip to main content

Event-Driven Programming

Event-driven programming is a paradigm where program flow is determined by events such as user actions, sensor outputs, or messages from other programs.

Core Concepts

Example: JavaScript

// Event listener
document.getElementById('button').addEventListener('click', (event) => {
console.log('Button clicked!');
event.target.style.background = 'blue';
});

// Custom events
class EventEmitter {
constructor() {
this.events = {};
}

on(event, callback) {
if (!this.events[event]) {
this.events[event] = [];
}
this.events[event].push(callback);
}

emit(event, data) {
if (this.events[event]) {
this.events[event].forEach(callback => callback(data));
}
}
}

// Usage
const emitter = new EventEmitter();
emitter.on('data', (data) => console.log('Received:', data));
emitter.emit('data', { message: 'Hello!' });

Advantages

✅ Responsive applications
✅ Loose coupling
✅ Asynchronous handling
✅ Scalable architecture

Use Cases

  • GUI applications
  • Web applications
  • Real-time systems
  • IoT devices