Thinking Outside the DOM: Concepts and Setup

Originally published at:

If I were to name one thing that most JavaScript code bases struggle with, it would be tight coupling in general, and coupling to the DOM in particular. Tight coupling causes developer headaches and problems when unit-testing the code.

In this two-part series, I will give you some hints on how to achieve loosely coupling code, and walk you through an example of how to detach your code from the DOM. In this first installment, I’ll introduce you to the problems of having a tightly coupled code and we’ll also walk through a real-world situation where we can apply the concepts discussed: the validation of a form.

What is coupling?

In many applications the code interacts with a variety of external APIs. In web applications, we interact with the DOM API, possibly the network (through XMLHttpRequest), JSON or XML for data exchange, and many others. On a conceptual level, these concerns are strictly separated from each other.

If the REST API your app interacts with makes a few structural changes, it’s reasonable that you’ll need to update the code interacting with the REST service. It isn’t reasonable that this requires changes in the UI rendering code. Yet, very often it does. And when that happens, you have what is called “tight coupling”.

Loose coupling is the opposite of tight coupling. In a loosely coupled system, changing network requirements does not cause changes in the rendering code. A revamped CSS stylesheet and new rules for class names does not cause changes in the data serialization code. This means fewer problems, and a code base that is easier to reason about.

Now that I’ve given you some context, let’s take a look at what this means in practice.

Continue reading this article on SitePoint

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.