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...