Saturday, September 5, 2009

jquery coding practices

I've been the lynda.com series on jquery. I learned jquery a year ago, didn't use it, and promptly forgot its syntax. So I'm grateful for the refresher.

I am curious about what I see as a common practice amongst seasoned jquery-writers: constant use of chaining and function literals. To be blunt, this looks like bad coding style to me.

This sort of thing I mean:


var whichTag = "h3";
var count = 0;

$("div:not([id=header]) " + whichTag).each(function() { $(this).html("" + $(this).html() )});


I see this chaining/inline-function style everywhere throughout the jquery community. It's in all the books, tutorials, etc. So I am wondering if there's a good reason for it. I may be stuck in my own rigid paradigm and I'm willing to consider other approaches.

Here's how I would write that code:



var whichTag = "h3";
var count = 0;
var tagFilter = "div:not[id=header]" + whichTag;

$each( tagFilter).each( makeAnchor );

function makeAnchor()
{
var anchorTag = "";
var oldTagContent = $html(this);
$this(html) = anchorTag + oldTagContent;
}



I would love to hear your thoughts. Is there a profound reason for writing (to me) hard-to-read code when writing it in jquery? Or is it just a convention that has cropped up (why?) in the jquery community?

1 comment:

  1. Speculation: possibly an attempt at minimizing whitespace to reduce the size of the file being transfered. But there are automated minimizers which do far more than get a rid of a little whitespace. Perhaps it's a compromise between complete illegibility and larger file sizes? I've only used jquery a little and have got to say that excessive chaining really slows down my comprehension of the code.

    ReplyDelete