Posts Tagged ‘bestpractices’

Making jQuery code readable

Wednesday, June 17th, 2009

As a long time jQuery user I use many of it’s features, and much more than just the most basic ones. I love it, especially when I find new tricks to simplify or shorten my code. But my code is most often only read by me.

Recently I’ve been working with developers new to jQuery, and it has come clear to me that my code – as simple and smooth I find it – is often hard to understand. I’ve gotten the same looks I would get presenting a Perl-golf program. Ah well, maybe not quite. But you get my point.

I have set to make my code more readable, without making it ugly. Below are a few best-practices I’ve made for myself.

Break down long chains

Here is a typical bit of code I might write:

$('table')
    .find('.activate').click(function () { activate(this.id) }).end()
    .find('.deactivate').click(function () { deactivate(this.id) }).end()
    .find('a').show();

Long chains of code tend to use jQuery commands like end and andSelf to modify the wrapped set. Those methods are good to have when you know them, but their semantics can’t be easily deducted from their names. A long chain performing many tasks can also be harder to walk through than smaller independent bits. So it is wise to break chains down:

var table = $('table');
$(table).find('.activate').click(function () { activate(this.id) });
$(table).find('.deactivate').click(function () { deactivate(this.id) });
$(table).find('a').show();

This version – without doubt – lacks the beauty of the chain above, but is more readable, especially to someone unfamiliar.

Bind events using explicitly using bind

Having the same method to bind and fire an event is bound to confuse – hell, I get confused again and again:

$('select')
    .change(function () { ... })
    .change();

Explicitly calling the bind command to bind to the change event is much easier to grasp:

$('select')
    .bind('change', function () { ... })
    .change();

This holds for all events who have shortcuts for binding, e.g blur, click and mousedown.

Clarify what this means

The this keyword is probably one of the most infamous elements in the JavaScript language. And even when you’ve gotten fluent in using it, you never can be quite sure it’s used the same way in the same contexts.

This is a typical code snippet:

$('a')
    .addClass('logged')
    .bind('click', function() {
        logUrl(this.href);
    });

What does this point to? This example is that simple, and the href attribute that specific, that it’s maybe not hard to guess. But in more complex situations it’s hard to find out.

Copying this to a clearly named variable does a great deal in clarifying what’s going on:

$('a')
    .addClass('logged')
    .bind('click', function() {
        var clickedLink = this;
        logUrl(clickedLink.href);
    });