Reader small image

You're reading from  Building SPAs with Django and HTML Over the Wire

Product typeBook
Published inAug 2022
PublisherPackt
ISBN-139781803240190
Edition1st Edition
Tools
Right arrow
Author (1)
Andros Fenollosa
Andros Fenollosa
author image
Andros Fenollosa

Andros Fenollosa is a custom programming expert that works as a teacher, full stack developer, and mobile developer. He's a Web Designer, Web Programmer, and Apps Programmer, among other things ( PWA, Android and iOS ). He has a plethora of commercial expertise, having worked on projects in a variety of locales throughout the world.
Read more about Andros Fenollosa

Right arrow

Chapter 8: Simplifying the Frontend

Throughout the chapters (e.g., doing the chat project or the blog), we wrote sloppy JavaScript code. We were forced to repeat tasks every time the backend sent new HTML, cleaning up orphaned events and reassigning new ones to the newly created DOM. Our ambitions with the frontend have been quite modest. We’ve limited ourselves to surviving by focusing all our energies on the Django code. If we had had a tool to handle events via HTML rendered by the server, the JavaScript code would have been less verbose and much easier to work with. It’s time to refactor the frontend, but we need help to do that.

Stimulus is ideal for the job. We are talking about a framework whose objective is to constantly monitor changes in the page by connecting attributes and events with functions that we indicate. We can create controllers that we will assign through datasets to the inputs or any other element that we need to incorporate an event. And, in...

Technical requirements

The example is based on the template we used in Chapter 4, Working with the Database:

https://github.com/PacktPublishing/Building-SPAs-with-Django-and-HTML-Over-the-Wire/tree/main/chapter-4/initial-template

The finished code can be found in the following repository:

https://github.com/PacktPublishing/Building-SPAs-with-Django-and-HTML-Over-the-Wire/tree/main/chapter-8

It is also recommended that you visit Stimulus’ own documentation to learn more about important concepts such as controllers, actions, and targets:

https://stimulus.hotwired.dev/handbook/

And, optionally, it’s recommended that you have a modern version of Node.js along with the latest version of npm. We will use it to install the Stimulus package, but we can also use the CDN.

CDN or Content delivery network

A CDN is a group of servers located around the world that work together to deliver content to users quickly and efficiently. It is used with static content...

Installing and configuring Stimulus

Before you can use Stimulus, you will need to download and install the framework. If you don’t want to complicate things, you can import it from its CDN. Just add the following script in the HTML template:

<script type="module" src=
https://unpkg.com/@hotwired/stimulus@3.0.1/dist/stimulus.js
> 

If you opt for this solution, you can ignore the rest of this section.

However, if you want to download Stimulus, which is very good practice, please note that it is available in the npm packages, so let’s install it with a command:

npm i @hotwired/stimulus

From here, you have three different configuration possibilities: using Webpack, using another build system, or using the native JavaScript module system. We are going to focus on the last option, using modules, to simplify your implementation and not add more complexity:

  1. Copy the Stimulus file to a folder inside static, for example, in the static/js...

Defining a controller

The purpose of the controller is to connect the DOM with JavaScript. It will bind the inputs to a variable and the events that we indicate to a function created inside the controller.

The structure is as follows:

import { Controller } from "../vendors/stimulus.js".
 
export default class extends Controller {
 
   // Variables linked to inputs.
   static targets = [ "input1" ]
 
   // Constructor or function to be executed when the
   // controller is loaded.
   connect() {
   }
   // Simple function
   myFunction(event) {
   }
}

We have imported the Controller class that belongs to the framework itself with a combination of import and from. Then, we created a class that extends Controller and is also accessible from an import (export default). Inside, we have an example of a target called input1 and...

Managing events with actions

Actions are a structure used by Stimulus to link events to controller functions. They are declared in the DOM by means of a data-action dataset with the following structure:

<div data-controller="aliasController">
<button
  data-action=
    "event->aliasController#functionOfTheController"
>Click me!</button>
</div>

It will only work if it is inside a controller with the same alias; you cannot place an action in DOMs outside the tree.

Following the example, we modify our button:

<input
  type="button"
  value="Transform"
  data-action="click->transformer#lowercaseToUppercase"
>

Let’s analyze what we have done with data-action, since it contains its own format that we must follow:

  1. The event is click. It could be any other event, such as a submit event if we were in a HTML <form...

Capturing references with targets

Stimulus connects to form inputs via targets, or a special dataset. Internally, Stimulus creates a variable that can be used anywhere in the controller. For example, we define in the DOM an alias called name:

<div data-controller="aliasController">
<input type="text" data-aliasController-target="name">
</div>

While in the controller, we define the following:

static targets = [ "name" ]

From here, I can call the target within any function/method in the following way:

this.nameTarget

As you can see, the alias is joined with the target text.

In the application we are developing, we have defined the target with the name myText:

static targets = [ "myText" ]

We update the DOM of the input as follows:

<input type="text" data-transformer-target="myText" 
  placeholder="Enter text">

The whole frontend is ready...

An application that converts text into uppercase letters

We have already simplified the frontend with Stimulus, installing, configuring, and implementing the tools provided by this fantastic framework. However, we still have one last step left in the application that converts the text from lowercase to uppercase: implementing the backend in the consumer.

Edit app/app_template/consumers.py with the following code:

from channels.generic.websocket import JsonWebsocketConsumer
from django.template.loader import render_to_string 
 
class ExampleConsumer(JsonWebsocketConsumer): 
    def connect(self):
        """Event when client connects"""
        # Accept the connection
        self.accept()
  
    def receive_json(self, data_received):
        ...

Summary

Our journey of learning HTML over the wire with Django comes to an end. We are now able to create SPAs in real time by gathering all the logic in the backend, avoiding duplicating tasks such as validations or HTML structures. We have relieved the frontend of a big responsibility; it now only needs to handle events or animations, thanks to Stimulus controllers and internal automation from datasets.

I would love to tell you that you already know everything you need to know, but the journey continues. The book is just a first push. There is still a lot of work ahead of you: practice, adopt Stimulus in your workflow (or any other similar framework), solve small difficulties typical of any SPA (such as managing when the user clicks on the back button in the history), explore other related protocols such as Server-Side Events, train your colleagues, convince your boss, define your line between backend and frontend (the infinite struggle of any web developer), and even adopt some...

Why subscribe?

  • Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals
  • Improve your learning with Skill Plans built especially for you
  • Get a free eBook or video every month
  • Fully searchable for easy access to vital information
  • Copy and paste, print, and bookmark content

Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at packt.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at customercare@packtpub.com for more details.

At www.packt.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Building SPAs with Django and HTML Over the Wire
Published in: Aug 2022Publisher: PacktISBN-13: 9781803240190
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
Andros Fenollosa

Andros Fenollosa is a custom programming expert that works as a teacher, full stack developer, and mobile developer. He's a Web Designer, Web Programmer, and Apps Programmer, among other things ( PWA, Android and iOS ). He has a plethora of commercial expertise, having worked on projects in a variety of locales throughout the world.
Read more about Andros Fenollosa