jQuery: site and application settings

When developing a large jQuery application, it's often useful to store the global settings of our application. I've encountered several problems especially with keeping track of the element sets of a given web site. Typically, there are a couple of common elements which always feature on a web site or application, including the header section, the footer section, the content section, the navigation section and so on. The problem is to have a fast and direct access to these elements.

We should store the reference to these elements not only to have a faster access to them, but also to improve the overall performance of our jQuery code. In fact, repeating $('#header') several times in our code is tedious, not to say annoying. So we could do something like this:

var APP = {

  settings: {
  
    header: $('#header'),
    navigation: $('#nav'),
    footer: $('#footer'),
    search: $('#search-form'),
    contact: $('#contact-form'),
    content: $('#content')
  
  
  }


};

Done that, every time we define a method or property within our application, we can have an easy and direct access to these settings:

var APP = {

  //...
  
  validateForm: function() {
  
    this.settings.contact.submit(function(e) {
    
      // validate form
    
    
      e.preventDefault();
    
    });
  
  
  }

};

The important thing is to define your settings within the namespace of your application. In this example I've used an object literal, but you can also use a self-instantiating function, thus creating another singleton:

var APP = new function() {

  var settings = {
    header: $('#header'),
    navigation: $('#nav'),
    footer: $('#footer'),
    search: $('#search-form'),
    contact: $('#contact-form'),
    content: $('#content')
  }; 



}();

settings has now become a private member of your application object, while in the previous example it was public. You can choose either this or the other approach, depending on your needs.

When you have to create another site or application, you can reuse this pattern for redefining your settings. This aids portability and reusability.

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.