Wednesday, March 21, 2012

How to "Chain" function calls in JavaScript

Every since I started using libraries like jQuery I was always fascinated on how you can chain function calls together.

For example:

In the above example after the menu div fades in the class "active" is added to it.

This makes for a nice 'flowing' feel to code writing, especially in JavaScript which is such a top-down code execution environment.

But I could never figure out how the libraries like jQuery could code such 'chain-able' functions. I did my research and at its core its not that complicated! (Although i'm sure the jQuery core is much more complicated)

Here is an example of a simple feature that makes a twitter API Ajax call to my twitter account and returns the results when its received.

getTweets = function(userName) {
  var doneCallback = function(tweets){
  alert('Response received but no callback function')

var url = '' + userName + '.json';

$.when($.get(url, {count:5}, null, 'jsonp')).done(function(tweetData){

return {
    done: function(f){
      doneCallback = f || doneCallback;

and here is how you call this function with a 'chained' done function that will execute once the results are returned:

  alert(tweets.length + " tweets received!")

  • The getTweets function has a dummy function called doneCallback which is executed once the jQuery ajax call is complete. (I'm using the $.when jQuery command which is way to respond to ajax calls after the ajax call is complete - its using the jQuery Deferred object system, which if you have not heard of, may be worth looking into, especially if you make a lot of ajax calls in your app)
  • The getTweets 'returns' an object which has a property called 'done' which is an anonymous function.
  • When we call getTweets("newbreedofgeek") and chain our '.done' function we are basically updating the above anonymous function of the returned 'done' property

I did this test after reading this article which gives a clearer explanation on this (read the section "Adding callback functionality to our preloadimages() function"):

 I've created a similar JSFiddle as the example above so you can play around with it.

No comments:

Post a Comment

Fork me on GitHub