Building a Proper MVC Pattern for the web

Search Google for “web application MVC patterns” or any variant thereof, and the vast majority of results will talk about the server side MVC. This traditional answer will tell you the browser sits outside the MVC altogether, and sends in HTTP requests that are handled by the Controller, then all the MVC garble happens, and finally the View spits out a brand new HTML page (or XML/JSON for AJAX) for the browser to consume. All this ends up looking something like:

“So what’s the problem with this model?” you ask? The JavaScript layer of course 😉 . All of the code that runs in the browser doesn’t fit anywhere inside the classic MVC architecture. What ends up happening is usually one of two things:

  1. All of the JavaScript in an app is completely unmanaged, and it ends up looking like spaghetti, or
  2. The server side View tries to manage and encompass everything that happens in the browser – including JS – and the code still looks like spaghetti

The “honest” version of the above diagram should really look more like this:

Clearly this isn’t any way to design an app. JavaScript and AJAX have become increasingly important in an application’s user interface, and many web apps entirely depend on it. There has to be a better way to organize the JavaScript in your app to be more efficient, testable, and most importantly – manageable.

What’s needed is to rethink web application architecture. What’s needed is a new MVC pattern- er, patterns.

The solution is to not only build an MVC on your server, but also a second MVC in JavaScript. Stop thinking of your web app as a web app. Instead – think of it as two: one in the browser and one on your server.

This architecture lets you isolate JavaScript code that’s inherent to AJAX and your data, letting you build a bridge between your JavaScript UI and your server. What’s more, it does it in an organized and manageable way.

Now all of your JavaScript UI code doesn’t need to be re-hacked every time you make a slight change to your AJAX responses, and all of your AJAX code doesn’t have to care about what div is updating or what widget is changing which other widget. Data code manages data, view code manages view, and a controller to tie it all together.

To demonstrate how easy it is to set up a client-side MVC, I’ve released my first JavaScript tutorial that walks through exactly this: creating an MVC in JavaScript using JQuery. I’ve also set up a tutorials section on the site (this being the only tutorial so far :P) and hope to expand over the coming weeks and months.

Also be sure to check out Listotron.com, a project Buck and I are starting that will be using exactly this architecture.

First image courtesy of Matt Chisholm – sort of – I modified it a bit. The other diagram is a photochop of it as well. Gliffy made the boxy image.