Tuesday, November 8, 2011

JavaScript Patterns: Settings object

One of the patterns you see a lot in jQuery and other JavaScript based framework is the use of a Settings object to pass configuration data to a module or function.
Again without spending too much words, a short sample:
(function ($) {
      $.fn.blink = function (options) {
      var settings = {
     'speed': 'fast', 
    'repeat': 3
        };
        //if the options isn’t null extend defaults with user options.
        if ( options ) { 
        $.extend( settings, options );
        }

        for(var i = 0;i<settings.repeat;i++)
        {
      this.fadeOut(settings.speed);
      this.fadeIn(settings.speed);
        }
      }
})(jQuery);


This is a function from a jQuery plugin(can’t remember the exact name). But the important things to notice here are:
  1. The blink method allows you to pass an options object.
     
  2. Inside the blink method a settings object is created with some default settings.
     
  3. If the user specified the options object, it will override one or more defaults by using the ‘extend’ method.
Learn it, love it…

No comments: