Geeks With Blogs
Krishna's weblog Frozen thoughts of a budding developer - jQuery, ASP.NET, AJAX and more...

The goal of this article is to educate budding jQuery developers (who do not have much exposure to JavaScript), to write clean, readable, maintainable code. This is in fact, a pointer to articles written by several JavaScript gurus.

For a jQuery developer, who does not have good expertise of JavaScript object oriented programming concepts, the entire code of a JavaScript file would reside in the "$(document).ready()” function. This includes various events, ajax calls, their call backs, UI effects etc.

In the case of a large scale business application (having hundreds of JavaScript files, each file having few thousands of lines), this would mean a lot of effort during reviews, white box testing and especially maintenance. Therefore, apart from learning the library, knowledge of good practices of core JavaScript language is a must.

Here is a collection of some of the best links, which would change the way you code. Read them in this sequence :)

1. JavaScript Best Practices by Christian Heilmannhttp://dev.opera.com/articles/view/javascript-best-practices/

2. Show love to the object literal - http://www.wait-till-i.com/2006/02/16/show-love-to-the-object-literal/

3. Closures and lexical scoping in JavaScript - http://mark-story.com/posts/view/picking-up-javascript-closures-and-lexical-scoping

4. Private Members in JavaScript by Douglas Crockford - http://www.crockford.com/javascript/private.html

5. JavaScript programming patterns - http://www.klauskomenda.com/code/javascript-programming-patterns 

6. Five things to do to a script before handing it over to the next developer - http://www.wait-till-i.com/2008/02/07/five-things-to-do-to-a-script-before-handing-it-over-to-the-next-developer/

Out of all the JavaScript design patterns in link #5, these are quite popular:

 a. Singleton pattern [Thanks to HB Stone for explaining the concept in simpler terms]

 b. Module pattern [Thanks to Christian Heilmann for the contribution]

 c. Revealing module pattern [An updation to module pattern by Christian Heilmann]

I have tried these and like many others, I fell in love with the Revealing module pattern. The core of these patterns is the concept of closures. So make sure you are good at the basics!

Before trying out patterns, my jQuery code was like this:

$(document).ready(function() {
   //page load ajax call 
    $.ajax({
        type: "POST",
        url: "CTypesHandler.ashx",
        data:"{}",
        success: callBackFunction,
        error: function(){}
    });
 
    //ajax success callback function
    callBackFunction(response)
    {
        //process ajax response here...
    }
    
    //form validation code
    $('#FormId').validate(){
        //code for validation
    }
    
    //click events
    $('#submitButton').click(function(){
      //code for submit click event
    });
    
    $('#saveButton').click(function(){
      //code for save click event
    });
});

After trying out Revealing Module pattern, my jQuery code is very clean like this:

var mySamplePage=function(){
    var counter=0;
    
    var callBackFunction = function(response)
    {
        //process ajax response here...
    };
    
    var pageLoadAjaxCalls=function(){
        $.ajax({
            type: "POST",
            url: "CTypesHandler.ashx",
            data:"{}",
            success: callBackFunction,
            error: function(){}
        });
    };
    
    var bindEvents=function(){
        $('#submitButton').click(function(){
          //code for submit click event
            counter++;
        });
        
        $('#saveButton').click(function(){
          //code for save click event
        });
    };
    
    var validate=function(){
      $('#FormId').validate(){
          //code for validation
      };
    };
    
    var pageLoadOperations=function(){
        validate();
        pageLoadAjaxCalls();
        bindEvents();
    };
    
    return{
        init:pageLoadOperations
    };   
}
 
$(document).ready(function(){
    vare page= new mySamplePage();
    page.init();
});

To explain the differences in short, the first snippet has all code in document.ready function. This means, all variables, functions used are global. There is no modularization in the code. So if new events, UI logic are to be added, they add up to the mess.

In the case of patterns snippet, the code is clearly modularized. There are no global variables/functions. All members, functions are private. Only certain methods are exposed(by adding pointer in return statement). If new code has to be added in future, it can be added to the respective functions (like pageLoadAjaxCalls, bindEvents etc). Our document.ready is now very clean, and has control on what to be done, with ease.

Using good jQuery selectors gives optimized code; Using JavaScript design patterns gives clean and maintainable code. Happy coding :)

Posted on Wednesday, October 28, 2009 6:34 PM jQuery , Web Development | Back to top


Comments on this post: Love JavaScript design patterns, love your jQuery code even more!

# re: Love JavaScript design patterns, love your jQuery code even more!
Requesting Gravatar...
Nice collection and examples. The maintainability of this type of pattern becomes even more obvious when you want to temporarily remove one section of code, or change the order in which things occur.

If you wanted to bind events before making the page load AJAX calls, in your pre-pattern example you may have to copy and paste a massive chunk of code, depending on how many events you're binding, how big those bound functions are, etc.

Post-pattern, you just swap two lines inside pageLoadOperations and you're done. Or comment out one line to temporarily skip an entire section of code. Super fast for debugging.
Left by HB on Oct 28, 2009 6:50 PM

# re: Love JavaScript design patterns, love your jQuery code even more!
Requesting Gravatar...
Very true HB!
Infact, there are few more additional advantages with these patterns.
In the traditional way, suppose I declared a function in document.ready, I cannot execute it at a later poing (e.g., call a function of parent screen in a modal popup like jqModal or BlockUI). This is because the scope of the function is restricted to document object.

But now, I can simply expose a public method in the "return" part and call it with a new instance of the constructor function. I can have full control over my page level methods, which are not having global scope :)
Left by NovoGeek on Oct 30, 2009 1:32 AM

# re: Love JavaScript design patterns, love your jQuery code even more!
Requesting Gravatar...
Nice information, many thanks to the author. It is incomprehensible to me now, but in general, the usefulness and significance is overwhelming. Thanks again and good luck!
Left by Compare hotels for cheapest prices on Nov 01, 2009 11:57 AM

# re: Love JavaScript design patterns, love your jQuery code even more!
Requesting Gravatar...
I personally have embraced the new technologies and the CMS platforms, I think the new tools only make the web designs better. I am glad that new technologies are coming out in web design that make things easier, improved, and better looking for design.
Left by Seattle DUI on Nov 03, 2009 11:10 AM

# re: Love JavaScript design patterns, love your jQuery code even more!
Requesting Gravatar...
Hey - nice blog, just looking around some blogs, seems a pretty nice platform you are using. I'm currently using Wordpress for a few of my sites but looking to change one of them over to a platform similar to yours as a trial run. Anything in particular you would recommend about it?
Left by mobile phones on Nov 03, 2009 4:35 PM

# re: Love JavaScript design patterns, love your jQuery code even more!
Requesting Gravatar...
Keep 'em coming... you all do such a great job at such Concepts... can't tell you how much I, for one appreciate all you do!
Left by Bulletproof Business Blueprint Review on Nov 05, 2009 12:54 AM

# re: Love JavaScript design patterns, love your jQuery code even more!
Requesting Gravatar...
Thanks for taking the time to discuss this, I feel strongly about it and love learning more on this topic. If possible, as you gain expertise, would you mind updating your blog with more information? It is extremely helpful for me.
Left by tragaperras on Nov 06, 2009 2:09 PM

# re: Love JavaScript design patterns, love your jQuery code even more!
Requesting Gravatar...
There are certainly a lot of details like that to take into consideration. That is a great point to bring up. I offer the thoughts above as general inspiration but clearly there are questions like the one you bring up where the most important thing will b
Left by custom wood signs on Nov 07, 2009 12:01 PM

# re: Love JavaScript design patterns, love your jQuery code even more!
Requesting Gravatar...
Just wanted to give you a shout from the valley of the sun, great information. Much appreciated.
Left by homeopathic remedies on Nov 10, 2009 4:55 PM

# re: Love JavaScript design patterns, love your jQuery code even more!
Requesting Gravatar...
Couldn?t be written any better. Reading this post reminds me of my old room mate! He always kept talking about this. I will forward this article to him. Pretty sure he will have a good read. Thanks for sharing!
Left by Michigan Car Insurance on Nov 11, 2009 7:53 PM

# re: Love JavaScript design patterns, love your jQuery code even more!
Requesting Gravatar...
I admire the valuable information you offer in your articles. I will bookmark your blog and have my children check up here often. I am quite sure they will learn lots of new stuff here than anybody else!
Left by Alice Springs Chicken on Nov 13, 2009 4:48 PM

# re: Love JavaScript design patterns, love your jQuery code even more!
Requesting Gravatar...
Valuable information and excellent design you got here! I would like to thank you for sharing your thoughts and time into the stuff you post!! Thumbs up
Left by new york giants tickets on Nov 14, 2009 6:40 PM

# re: Love JavaScript design patterns, love your jQuery code even more!
Requesting Gravatar...
You really make it seem so easy with your presentation but I find this topic to be really something which I think I would never understand. It seems too complicated and very broad for me. I am looking forward for your next post, I will try to get the hang of it!
Left by pink digital cameras on Nov 15, 2009 2:14 PM

Your comment:
 (will show your gravatar)


Copyright © novogeek | Powered by: GeeksWithBlogs.net