The MVC pattern is quite often used on the server-side when writing web applications, for instance ASP.NET, PHP, Ruby on Rails.

Being a JavaScript developer, I am wondering whether we should segment our JavaScript code, the client tier of our web applications, into similar Model-View-Controller structures, or not. Is there really a need of this pattern on the client side?

1 Answers

JavaScript frameworks like jQuery, Prototype, ExtJS, and DOJO have simplified the way you handle the DOM and JavaScript. You can encapsulate visual portions of the DOM and deal with events in a uniform way. Although they have greatly facilitated in structuring the client tier, there must be a way to deal with the situation when the complex client-side code gets messy very fast and at the same time maintainability, testability, and reusability is significant. A more structured approach to writing complex JavaScript apps is required. As your JavaScript app becomes complex and its scale increases, you require a pattern like MVC in place.

Without MVC, the JavaScript code muddles up AJAX calls, DOM manipulation, and event handling. Instead of placing all the code collectively in one single place, you should be able to define individual objects for each. If your program wants to send the queries to the server or retrieve data from the browser's local storage or cookies, then you can create a model object where this should happen. In fact, the model is the only entity in the entire program that should know anything about Ajax calls. But the model should not be responsible to interpret the response that is sent back from the server and populate the HTML page with the results. It should know nothing about the DOM manipulation. It is the view object that manipulates the DOM tree and builds the HTML page. The controller updates the view when the model changes. It also registers the event handlers with the view and updates the model when the user manipulates the view.