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.
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!
by Bunzli on December 2, 2010 at 14:04