My favorites | Sign in
Logo
                
Search
for
Updated Aug 06, 2009 by matr...@mac.com
Chaining  
Description of Chaining

Chaining

Chaining is a concept which allows you to write simple human-readable JavaScript code with minimum mess and minimum lines.

Made famous by jQuery, chaining is a pattern where each method call returns the object so other methods can be added (chained) to the end.

The old style

objx supports the non-chaining approach too:

// create a list
var myList = [1,2,3];

// wrap it in objx
var o = objx(myList);

// store the total
var total = 0;

// total the items in the list
o.each(function(item){ 
  total += item; 
});

// convert the array to a string
o.type("string");

// get the string
var s = o.obj();

The chaining approach

We can do the same job as the code above by utilising the chaining model and wrapping up a few other things:

var total = 0;
var s = objx([1,2,3]).each(function(item){ total += item; }).type("string").obj();

Finding the sweet spot

If the fully chained version looks too complicated or if you miss the comments, you can always split it across multiple lines:

var total = 0;
var s = objx([1,2,3])

   // total them up
   .each(function(item){ total += item; })

   // convert the array to a string
   .type("string")

   // and set the object to 's'
   .obj()
;

Sign in to add a comment
Hosted by Google Code