2009 Nov 20 @ 2:39pm underscore.js jquery

Underscore.js

I’ve been playing with Underscore.js a bit lately. “It’s the tie to go along with jQuery’s tux.” It is not a jQuery plugin nor does it require jQuery in any way. But it is designed to complement jQuery.

About half of Underscore’s 50-ish functions are for working with collections and arrays. Another subset work with objects (comparisons, evaluations, etc.).

However, I’ve been looking at one of Underscore’s utility functions, template. It’s useful for formatting output of asynchronous calls that return JSON.

Suppose you have a User data structure and each User has a Title, a Name, and an EmailAddress. You might setup a server-side script that returns JSON that looks like:

[
    {
	"Title": "Mr.",
        "Name": "John Smith",
	"EmailAddress": "john@smith.com"
    },
    {
	"Title": "Mrs.",
        "Name": "Jane Smith",
	"EmailAddress": "jane@smith.com"
    }
]

Using jQuery, you could add that to your page like so:

$.getJSON
(
    "Users.json",
    function(users)
    {
        $.each
        (
            users,
            function()
            {
                appendUser(this);
            }
        );
    }
);

function appendUser(user)
{
    tr = $("<tr/>").appendTo("tbody#Users");

    $("<td/>").appendTo(tr).text(user.Title);
    $("<td/>").appendTo(tr).text(user.Name);
    $("<td/>").appendTo(tr).text(user.EmailAddress);
}

Or you could rewrite appendUser to use Underscore’s template function like so:

function appendUser(user)
{
    $("tbody#Users").append(_.template("<tr><td><%= Title %></td><td><%= Name %></td><td><%= EmailAddress %></td></tr>", user));
}

This idea isn’t new. You can trace it back to John Resig’s micro-templating (and earlier), but Underscore packages it up nicely into a single function call that isn’t bound explicitly to jQuery as a plugin.