JQuery Style Function Chaining

JQuery Style Function Chaining

As I just posted, I recently had the chance to add JQuery style function chaining to my Spatial Query javascript library. By function chaining, I mean the ability to do something like this:

$("div.of_interest").css("border", "solid 1px black").show()

A useful technique in situations where you plan on performing multiple operations on a given set of data.

I went straight to the source to determine how to create that sort of functionality - the JQuery source, mirrored on GitHub by JackDanger.

The relevant code was in jquery/src/core.js. The simplified version of the technique could be stated like:

var jQuery = function(selector, context){
  return new jQuery.fn.init(selector, context);

jQuery.fn = jQuery.prototype = {
  init : function(selector, context){
      Acquire the elements in question
    return this;
  // The rest of jQuery's functionality would
  // be defined in this prototype, such as
  // .each, .find, etc.


jQuery.fn.init.prototype = jQuery.fn;

The line of particular interest is the line:

jQuery.fn = jQuery.prototype = { // etc.

Here we assign the prototype to a separate variable, jQuery.fn, in order to refer to its members (namely the init function) in the main jQuery function. Then, in order to make sure that new instances of jQuery.fn.init have the methods declared in jQuery.prototype, we assign the jQuery.fn.init.prototype to the jQuery.prototype.

Now at this point, the jQuery function can return instances of "itself". In order to chain from one function to the next, functions of the jQuery.prototype will either return this or jQuery(collection_of_elements) to allow the chain to continue.

There are lots of other cool techniques in the jQuery source - they're obviously having fun pushing Javascript to what limits they can find. :-)

comments powered by Disqus