Servage Magazine

Information about YOUR hosting company – where we give you a clear picture of what we think and do!

Element-specific data handling for jQuery plugins

Monday, November 29th, 2010 by Servage

The jQuery Plugin Authoring documentation uses the following example for usage of options for a plugin:

(function( $ ){
  $.fn.tooltip = function( options ) {
    var settings = {
      'location'         : 'top',
      'background-color' : 'blue'
    };
    return this.each(function() {
      // If options exist, lets merge them
      // with our default settings
      if ( options ) {
        $.extend( settings, options );
      }
      // Tooltip plugin code here
    });
  };
})( jQuery );

When using element-specific data with the data() method from jQuery, the documentation suggests the following usage:

    return this.each(function() {
      // If options exist, lets merge them
      // with our default settings
      var data = $(this).data('pluginData');
      if ( options ) {
        data = $.extend( settings, options );
        $(this).data('pluginData', data);
      }
      // Tooltip plugin code here
    });

However, there is a problem with this, because the $.extend() method actually doesn’t return a new object, but merges the passed objects into the first object. Thereby passing options for a specific instance of the plugin, actually overrides the default plugin options for all following plugin instances – which is a problem when using a jQuery plugin multiple times on the same page with different options. Therefore the usage of $.extend() should be modified to something like this:

data = $.extend({}, settings, options );

By passing an empty object as the first parameter to $.extend() you don’t override the defaults, but create a new object with the merged options – so the defaults remain the same for each plugin instance, unless they are modified when calling the plugin.

Element-specific data handling for jQuery plugins, 4.0 out of 5 based on 8 ratings
You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

1 comment (leave a comment)

For a long time I’ve been wondering what i’m doing wrong when creating jQuery plugins. It seems that the official documentation has some bugs… Thanks!

Leave a comment

You must be logged in to post a comment.