jQuery Standards (8) – Chaining

Synopsys

Use chaining as an alternative to variable caching and multiple selector calls.

Where chaining is used, appropriate line breaks and indentation should be used.

Do not over-chain. For long chains it acceptable to cache intermediate objects in a variable.

Description

Chaining is one of the signature features of jQuery. Used correctly, it can reduce the amount of code we have to write and the amount of data that is held in memory.

Chaining can be considered as an alternative to:

  • Caching jQuery objects in local variables
  • Performing multiple selections

Where chaining is used, appropriate line breaks and indentation should be used.

When to Use Chains

Chains should not compromise the readability of the code. For long chains, finding and defining a formatting and indentation strategy can be troublesome.

It can be better in these instances to cache your jQuery object in a separate variable.

When a JavaScript object is cached in jQuery, the reference to the object is actually stored. This occupies a minimal amount of memory, leaving negligible performance degradation.

The items show some indentation strategies, and a representation with a cached variable:

Chain Formatting Examples

Long Chains – Indentation Strategy 1

$("#MyTable").append(
    objButton.parents("tr").clone()
        .find(".RowTitle")
            .text("Row " + String(AddCount)).end()
        .find(".MySelect1")
            .attr("id", "SomeId" + String(AddCount))
                .change(function() { ChangeFundRow() }).end()
        .find(".MySelect2")
            .attr("id", "SomeOtherId" + String(AddCount)).end()
);

Long Chains – Indentation Strategy 2

$("#FundTable").append(
    objButton
        .parents("tr")
            .clone()
                .find(".RowTitle")
            .text("Row " + String(AddCount))
            .end()
                .find(".MySelect1")
                .attr("id", "SomeId" + String(AddCount))
                .change(function() {
                    ChangeFundRow();
                })
            .end()
                .find(".MySelect2")
                .attr("id", "SomeOtherId" + String(AddCount))
            .end()
);

To the untrained eye, either of the above may take some deciphering. In this case, a better strategy could be to cache your selections in a separate variable:

Long Chains – Caching Variable

var $clonedRow = objButton.parents("tr").clone();
$clonedRow.find(".RowTitle")
          .text("Row " + nAddCount); 

$clonedRow.find(".MySelect1")
    .attr("id", "FundManager" + nAddCount)
    .change( ChangeFundRow ); 

$clonedRow.find(".MySelect2")
          .attr("id", "FundName" + nAddCount); 

$clonedRow.appendTo("#FundTable");

jQuery Coding Standards Menu

  1. jQuery Variables
  2. DOM Manipulation
  3. Events
  4. Page Style and Layout Changes
  5. Effects and Animation
  6. Selectors
  7. Plugins
  8. Chaining