I’ve been thinking a lot lately about the emerging patterns in web development in the post Web 2.0 world. AJAX and javascript are mainstream now and no longer just parlor tricks. It is de rigueur to implement RESTful web services and have an API. But with all these AJAX calls whizzing about and JSON, XML, HTML, and whatnot being passed to and fro, it is easy to end up with a tangled mess. The one thing about mixing your web framework with javascript is that you now have a lot of code going on that leaks outside of your nice, neat Model-View-Controller (MVC) pattern.
I have seen javascript used extremely sparingly in an application all the way up to extremely heavy usage with javascript controlling not only logic but the entire layout of the page. But to keep a nice separation of responsibilities I believe the server side code should be responsible for laying out the structure of a page. We can then componentize the dynamic data bits and create a nice structure whereby javascript widgets are responsible for making AJAX calls to fill in those components.
For example, you have a page which is rendered by your MVC framework. But on that page is a div that contains a list of dynamic data. When the page is rendered there is just a placeholder for the list. Using JQuery event handlers you then make an AJAX call to fetch the data from your own RESTful API and populate the div.
What I like about this pattern is:
- you still have a strong MVC pattern
- you are eating your own dog food in terms of your API
- initial page loads are quick
- you can constantly poll for new data to give your application a real-time feel
An important point to note in this pattern is that you can still have your MVC framework responsible for rendering the data into HTML. Your RESTful API should accept a format parameter to set whether the return type is JSON, XML, or HTML. Internally, your own application can use the HTML return data type so that you do not have to write a bunch of javascript to turn the JSON into HTML. This way you can keep all your markup in templates and not scattered in javascript code.