Share
Explore

Web Front End Event Emitters Lab

\section{Event Emitters} Event Emitters are one of the key aspects of Node.js. It is the core concept behind the "non-blocking" nature of Node.js. Here's a small demo program to illustrate the creation and use of Event Emitters
\section{Create our own events and listeners} In Node.js, events are driven by the EventEmitter class. Let's create a new script to illustrate how we can leverage the EventEmitter class to create our own events and listeners.
\begin{lstlisting} // Import the events module const events = require('events');
// Create an instance of the EventEmitter class const myEmitter = new events.EventEmitter();
// Define a custom event and an associated listener myEmitter.on('greet', function(data) { console.log(`Hello, ${data}!`); });
// Emit the custom event myEmitter.emit('greet', 'World'); \end{lstlisting}
To run this code, save it as `eventEmitterDemo.js` and run it using Node.js:
\begin{lstlisting}[language=Bash] node eventEmitterDemo.js \end{lstlisting}
You should see `Hello, World!` printed to the console. The code above demonstrates a fundamental aspect of the EventEmitter API - defining custom events and emitting them. You can define as many events as you want, and even pass data when emitting an event.
\newpage \subsection{Changing Text Content in a Paragraph Element on Button Click: A JavaScript Demo}
Here's an example of a simple HTML page with a button and a paragraph. When the button is clicked, the text in the paragraph with id 'peanut' changes.
\begin{lstlisting}[language=HTML] <!DOCTYPE html> <html> <head> <title>Button Click Demo</title> </head> <body> <button id="myButton">Click Me</button> <p id="peanut">Original Text</p>
<script> document.getElementById('myButton').addEventListener('click', function() { document.getElementById('peanut').textContent = 'Text after button click'; }); </script>
</body> </html> \end{lstlisting}
\subsection{Explanation}
This is a simple HTML page with a button and a paragraph. We assign the button an id of 'myButton' and the paragraph an id of 'peanut'.
In the script tag, we use `document.getElementById('myButton')` to get a reference to the button. We then add an event listener to the button for the 'click' event.
When the button is clicked, the event listener function is called. Inside this function, we use `document.getElementById('peanut')` to get a reference to the paragraph. We then change the `textContent` property of the paragraph to 'Text after button click', thus changing the text in the paragraph.
\newpage

Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.