|
Chaining
Description of Chaining
ChainingChaining 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 styleobjx 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 approachWe 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 spotIf 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