Friday, September 7, 2012

The mochila pattern

A mochila (pronounced mo-chee-uh is Spanish for pouch) was used for carrying mail by the Pony Express in the nineteenth century. I'm discussing a technique of combining related HTML snippets into one HTML response by wrapping each of the snippets into separate envelopes. This single HTML response that contains multiple envelopes is a mochila. This technique can reduce the number of HTTP requests you need, and offers the ability to re-use existing partials without needing to create a JS template that duplicates a partial.

The example I'll use to illustrate the mochila pattern is an index page that shows a list of video thumbnails. When you hover over a thumbnail, it plays in the foreground while another version of the same video plays fullscreen in the background. The background video has a beautifully subdued alpha and gradient overlay. And the effect adds lots of interest and an artful quality to our page.

In our page the thumbnail video and the background video are separate HTML elements that live on different parts of the page. The background videos are just inside the body tag. The thumbnails are inside of an unordered list. However they are clearly related. If we want to add another video to the page with ajax we need to add snippets of HTML to both the list and the body for the respective new thumbnail and background videos. Here is the skeleton markup to illustrate that:
There are many ways we could add another video dynamically: multiple requests, json requests that populate JS templates, but we're interested in using a mochila. Here is a simple illustration of the technique:

Note how we can use jQuery to manipulate the HTTP response just like we would use it for any other part of the page.  This makes it simple to grab the separate envelopes from the mochila.  I think the other techniques have their place as well.  If you've already got a JS templating system in place, that can be a powerful technique.  But for a simple rails app you might be content to use this technique to get a little more mileage from your already built partials.

Like any technique the mochila can be abused. Filling a mochila with unrelated content or too many envelopes could create confusion and would lead to ugly JS pre-processing on the client. Add this trick to your arsenal, but don't abuse it.  Know your options.  Have a look at underscore.js templates if you haven't already.