Reader small image

You're reading from  Hands-on JavaScript for Python Developers

Product typeBook
Published inSep 2020
Reading LevelIntermediate
PublisherPackt
ISBN-139781838648121
Edition1st Edition
Tools
Right arrow
Author (1)
Sonyl Nagale
Sonyl Nagale
author image
Sonyl Nagale

Chicago-born, Iowa-raised, Los Angeles-seasoned, and now New York City-flavored, Sonyl Nagale started his career as a graphic designer focusing on web, which led down the slippery slope to becoming a full-stack technologist instead. With an eye toward the client use case and conversation with the creative side, he prides himself on taking a holistic approach to software engineering. Having worked at start-ups and global media companies using a variety of languages and frameworks, he likes solving new and novel challenges. Passionate about education, he's always excited to have great teachable moments complete with laughter and seeing the Aha! moments in students eyes.
Read more about Sonyl Nagale

Right arrow
Events, Event-Driven Design, and APIs

At the heart of a frontend application are events. JavaScript allows us to listen for and react to user and browser events to change content for the user in an intuitive fashion to create elegant user interfaces and experiences. We need to know how to use these packets of data that are thrown around. Browser events are our bread and butter—they allow us to have more than a static application and, instead, be dynamic! By understanding events, you'll be on your way to becoming a full JavaScript developer.

The following topics will be covered in this chapter:

  • The event life cycle
  • Capturing an event and reading its properties
  • Using Ajax and events to populate API data
  • Handling asynchronicity

Technical requirements

The event life cycle

When an event occurs in JavaScript, it doesn't simply happen and vanish—it goes through a life cycle. There are three phases to this life cycle:

  • The capture phase
  • The targeting phase
  • The bubbling phase

Consider the following HTML:

<!doctype html>
<html>

<head>
<title>My great page</title>
</head>

<body>
<button>Click here</button>
</body>

</html>

We can visualize it as follows:

Figure 7.1 – The event life cycle

Now, there's something else that is important to consider when it comes to events: they don't just take effect on the exact target, but rather on the whole stack of objects. Before we describe what capturing, targeting, and bubbling entail, take a look at the following representation of our code:

Figure 7.2 – Event layering

If we think about our page as a layer cake, we can see that this event (represented by the arrow) must pass through all the layers of our...

Capturing an event and reading its properties

We'll continue working with our events playground code: https://github.com/PacktPublishing/Hands-on-JavaScript-for-Python-Developers/blob/master/chapter-7/events/index.js.

On lines 32–34, we registered three click event listeners, as shown:

document.querySelector('html').addEventListener('click', logClick, true)
document.querySelector('body').addEventListener('click', logClick)
document.querySelector('button').addEventListener('click', logClick)

As we discussed, the first one is listening in the capture phase because we've included the final Boolean parameter.

We also have three mousemove events on lines 16–29. Let's take a look at one of them:

document.querySelector('button').addEventListener('mousemove', (e) => {
document.querySelector('#x').value = e.x
document.querySelector('#y').value = e.y
})

I hope most...

Using Ajax and events to populate API data

Let's put it all together. For this lab, we're going to be creating a simplified Pokémon game using PokéAPI: https://pokeapi.co/.

Here's what our game will end up being: https://sleepy-anchorage-53323.herokuapp.com/. Go ahead and pull up the site and play around with it to see the functionality.

Please resist the temptation to look at the finished JavaScript file (for now).

Here's a screenshot of what you'll see when you access the preceding URL and start playing the game:

Figure 7.7 – Pokémon game

All of the HTML and CSS have been provided for you. You'll be working in the main.js file: https://github.com/PacktPublishing/Hands-on-JavaScript-for-Python-Developers/tree/master/chapter-7/pokeapi/starter-code.

If you're not familiar with Pokémon, don't worry! The logic behind this game is basic. (If you are familiar with the games, forgive the simplified approach.)

Here's...

Handling asynchronicity

As we can see when using APIs, the asynchronous nature of Ajax calls for a couple of creative approaches. In our Pokémon game, we used a loading spinner while calls were completing; this is an approach you've seen all around the modern web. Let's take a look at one example from the game:

toggleLoader() {
/**
* As this is visual logic, here's the complete code for this function
*/
if (this.loader.style.visibility === 'visible' ||
this.loader.style.visibility === '') {
this.loader.style.visibility = 'hidden'
} else {
this.loader.style.visibility = 'visible'
}
}

All this part of the code is doing is toggling the visibility of a layer that contains a spinning image. This is all in the CSS (as it's not technically an image, but rather a CSS animation). Let's look at how it's used:

getPokemon() {
fetch('https://pokeapi.co/api/v2/pokemon?limit=1000')
.then((response...

Summary

We've learned about events, their life cycle, and how event-driven design works. An event is triggered by an action by the user (or programmatically based on the program logic) and enters its life cycle. In the event life cycle, our program can pick up on many pieces of information carried by the event object itself, such as the mouse position or target DOM node.

By understanding how Ajax works with events, you're well on your way toward becoming a fully fledged JavaScript developer. Ajax is incredibly important as its the conduit between JavaScript and external APIs. Since JavaScript is stateless and client-side JavaScript has no concept of sessions, it's important for Ajax calls to be asynchronous in nature; hence the introduction of tools such as fetch.

Congratulations! We've covered a lot of very dense material. Next up are frameworks and libraries in JavaScript.

Questions

Answer the following questions to gauge your understanding of events:

  1. Which of these is the second phase of the event life cycle?
    1. Capturing
    2. Targeting
    3. Bubbling
  2. The event object provides us with which of the following? – Select all that apply:
    1. The type of event triggered
    2. The target DOM node, if applicable
    3. The mouse coordinates, if applicable
    4. The parent DOM node, if applicable

Look at this code:

container.addEventListener('click', (e) => {
if (e.target.className === 'box') {
document.querySelector('#color').innerHTML =
e.target.style.backgroundColor
document.querySelector('#message').innerHTML = e.target.innerHTML
messageBox.style.visibility = 'visible'
document.querySelector('#delete').addEventListener('click', (event) => {
messageBox.style.visibility = 'hidden'
e.target.remove()
})
}
})
  1. Which JavaScript features ae used in the preceding code? Select...

Further reading

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Hands-on JavaScript for Python Developers
Published in: Sep 2020Publisher: PacktISBN-13: 9781838648121
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Sonyl Nagale

Chicago-born, Iowa-raised, Los Angeles-seasoned, and now New York City-flavored, Sonyl Nagale started his career as a graphic designer focusing on web, which led down the slippery slope to becoming a full-stack technologist instead. With an eye toward the client use case and conversation with the creative side, he prides himself on taking a holistic approach to software engineering. Having worked at start-ups and global media companies using a variety of languages and frameworks, he likes solving new and novel challenges. Passionate about education, he's always excited to have great teachable moments complete with laughter and seeing the Aha! moments in students eyes.
Read more about Sonyl Nagale