Originally published at: http://www.sitepoint.com/thinking-outside-dom-concepts-setup/
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.