The producer-consumer pattern is used when two parts of a system need to communicate.
They communicate via a queue or buffer:
The event driven programming paradigm is based on the producer-consumer pattern.
The event loop is a loop that runs through the entire lifetime of a program.
The process goes like this:
We can simulate an event loop in Python using a
while
loop and a list of events. We will:
Event driven programming is a common paradigm in GUI development, where we need to respond to user input.
The web browser has an event loop running that listens for events like:
Event | Description |
---|---|
click |
User clicks on an element |
mouseover |
User moves the mouse over an element |
mouseout |
User moves the mouse off an element |
focus |
User focuses on an element |
keydown |
User presses a key |
load |
Page has finished loading |
close |
Window is closed |
In JavaScript, we can add event listeners to elements in the DOM (Document Object Model) to listen for these events.
mouseover
// Get the header element for this section
const h2Examples = document.getElementById("javascript-examples");
// When the mouse is over the header, change text to all caps
h2Examples.addEventListener("mouseover", function (e) {
e.target.innerText = e.target.innerText.toUpperCase();
});
// When the mouse leaves the header, change text to all lowercase
h2Examples.addEventListener("mouseout", function (e) {
e.target.innerText = "JavaScript Examples";
});
click:
// Get all h2 elements on the page
const h2Elements = document.getElementsByTagName("h2");
// Loop through all h2 elements and add an event listener
for (let i = 0; i < h2Elements.length; i++) {
h2Elements[i].addEventListener("click", function (e) {
// e.target is the element that was clicked
// print the text of the element that was clicked
alert(e.target.innerText);
});
}