HTML, CSS and JavaScript: Model, View, Controller

From the point of view of web development we are all accustomed to the traditional distinction between structure, presentation and behavior. Although this model seems to be fairly accurate, it doesn't take into account the interactions occurring between these three layers. In fact, JavaScript can actually modify the structure of a document by adding new HTML elements or change their visual appearance using its style properties and methods. CSS, on the other hand, can modify the way an underlying HTML structure is perceived by readers by making elements visible or invisible or changing the element's disposition on the page. Is this presentation or something more? Is this only behavior or something else? It is clear that the traditional, three-layered model cannot take into account all the possibilities that may occur whenever these three components start interacting together.

For that reason, I propose to reformulate the old, layered model into the Model-View-Controller (MVC) pattern, borrowed from OOP (Object-Oriented Programming). In this model, each layer is called a component which interacts with other components to make the entire model work. At a very basic level, HTML (Model) provides the very basic functionalities to other components, such as page elements or DOM structure. The role of CSS (View) is to render the page according to the structure provided and, in turn, to the actions triggered by JavaScript, which represents the Controller component in this model. In fact, JavaScript can work both with HTML and CSS in response to the interactions occurred between the other two components. For example:

HTML (Model)


<div id="test"></div>

CSS (View)

.empty {

    background: yellow;
    
}

JavaScript (Controller)


var test = document.getElementById('test'); // accesses the Model

if(!test.hasChildNodes) {

    // controls the Model
    
    test.className = 'empty'; // works with CSS to change it
    
}

After accessing the underlying structure, JavaScript uses a CSS class to change the final view of the element taken as example. Even though this model differs greatly from the original OOP one, it's worth mentioning that its further applications are incredibly useful.

Leave a Reply

Note: Only a member of this blog may post a comment.