Search code examples
jqueryslidesjs

SlidesJS Source - Overriding defaults with specified options


SlidesJS is a jQuery content-slider plugin. I am trying to understand the source. I am relatively new to Javascript and jQuery. However, what I am interested in, is this line in the source code:

$.fn.slides = function( option ) {
   // override defaults with specified option
   option = $.extend( {}, $.fn.slides.option, option );
      ...
}

I understand by the comments that the author intends to merge two arrays, one containing the default values for option and the other is the option argument passed through calling the function. However, don't they both refer to the same variable: the argument of the function slides(option)?

It seems to work anyway. What's the magic here?


Solution

  • The option argument is an Object that contains corresponding setting values for the plugin. $.fn.slides.option contains the default settings for the plugin. So when you pass your custom settings (via the option parameter), these two objects are merged and your custom values overwrites the defaults.

    The jQuery.extend method is the key here. It merges the contents of two or more objects together into the first object.

    option = $.extend( 
                  {}, // the target new Object which represents the final merged options
                  $.fn.slides.option, // Object with default option values
                  option // Object with custom option values (the passed argument)
             );
    

    See documentation here.