What is Event-Driven Programming?
Event-driven programming is an approach to programming that focuses on delegating events to matching event handlers. An event can take the form of a button click, a message being passed between a thread or program, or any other action within a system that can be abstracted into an "event".
An event-driven program typically consists of a main-loop that listens for events to occur, and sends an event to a scheduler to decide which event-handlers to trigger. Modern languages or frameworks that offer event-driven actions take care of most of this work behind the scenes such as JavaScript. As a result, the actual flow of execution is difficult to be seen, and programs written in event-driven styles are seen more as a collection of event handlers.
<div style="width:100%;margin:auto;text-align:center"> <img src="https://www.devmaking.com/img/topics/paradigms/EventDrivenProgramming.png" alt="Class hierarchy" style="width:600px; max-width:95%;"> </div>
Typically, events will contain data about the action that has taken place, such as the name of a button being clicked, the key being pressed, or the data being submitted. Most frequently you will see event-driven programming being used with GUIs to help simplify event capturing.
Example: EventListeners in JavaScript
If you use the internet, it's almost guaranteed you interact with event listeners every time you navigate to a website or click a button. To get a grasp for the event-driven paradigm, let's take a look at how we can add an event to an html button. Let's say we have the following HTML that defines a basic button for our page:
<input type="button"
value="Click me!"
id="myCoolButton">
it'll display a native button with the text "Click me!", and we've also given it an id
so we can find it in our code:
var myButton = document.getElementById('myCoolButton');
function clickFunction(event) {
console.log(event);
console.log("The button was pressed!");
}
myButton.addEventListener("click", clickFunction);
Our myButton
element now has an event listener added to it that will look for any time that a "click" event is registered on that particular button, and execute our clickFunction
.