jQuery : Chaining of your custom function calls

04 / Jun / 2010 by Amit Jain 0 comments

Hi Friends,

I always used to think how jQuery provides the chaining mechanism, must be something really complex so never cared to find it out. Though there was a desire to to use the same concept in my own custom javascript functions. Recently I realised how easy it is, so thought would share with you with the help of an example.

jQuery.fn.getStudents= function(count) {  //count is the parameter name and getStudents is the function name.
//write your code here
...
return myObject  //return is optional
});

Now we can access the above function using dot operator on jQuery Object.

jQuery("#myListId").getStudents(5);

Please make a note the object returned by the previous function is made available to the chained functions as “this” object, that is one of the reason chaining became so useful. So in the above function getStudents(), “this” object would refer to the object returned by jQuery(“#myListId”).

Remember, to have chaining upto multiple levels, it becomes the obligation for the calling function to must return an object/value to the chained function being called on it.

jQuery.fn.highlightNames= function() {
//write your code here
jQuery(this).find(...);
...
});

Now we can access the above function i.e highlightNames() using dot operator even on another function.

jQuery("#myListId").getStudents(5).highlightNames();

Here I didn’t have to passes the students object to highlightNames, as it was available as a “this” object.

Hope it helped!

~~Amit Jain~~
amit@intelligrape.com
http://www.tothenew.com

FOUND THIS USEFUL? SHARE IT

Leave a Reply

Your email address will not be published. Required fields are marked *