Friday, November 18, 2011

Javacript Chaining

Javascript chaining pattern is the process of stringing methods/functions together without
having to recall the object. jQuery made this pattern famous.

jQuery Example:
$('div').css('color','red').html("I'm a second chain");

How to create your own:

var chain = {
first: function(){ //a method
alert("I'm first");
return this; //this is the secret
},
second: function(){ //another method
alert("I'm second");
return this; //this is the secret
}
}

//The chain
chain.first(); //alerts only the first
chain.first().second().first(); //alerts first,second and first(order insensitive)
This benefits you because the object doesn't need to be rewritten every time you want to use a method, resulting in less code. Call it once and add the methods to it.

The secret lies in returning the object (this). It resets the object allowing the next chain to use it.

No comments:

Post a Comment