Working with JavaScript requires understanding how events work. Writing evented JavaScript requires familiarity with callback functions.
With events, you write code that says "when this happens, run this function". For example, a user clicks a button on your web page which makes a modal window appear.
In both the browser and in node.js, you can write code that listens for and responds to various events.
There are three components to writing an event listener in JavaScript:
- The event target (in node.js, this is called an emitter)
- The type (or name) of the event
- The callback function to run when the event happens (or fires)
Here is an example of an event listener in the browser:
<html>
<body>
<button id="click-me">Press</button>
</body>
<script type="text/javascript">
var button = document.getElementById("click-me");
button.addEventListener('click', function(evt) {
alert('You clicked me!');
});
</script>
</html>
In the code above, the button
is the event target (the button element that
will fire the event), 'click'
is the event type (when the button is
clicked, it fires this type of event), and the function
function(evt) {
alert('You clicked me!');
}
is the callback (the code that runs when the event is triggered).