Reputation: 265
how can I assign a value to the 'extraParams' property of the following plugin 'defaults' object, from outside the plugin?
(function ($) {
jQuery.fn.jScroller = function (store, parameters) {
var defaults = {
//numberOfRowsToRetrieve: 10,
onSuccessCallback: function (row, container) { },
onErrorCallback: function (thrownError) { window.alert('An error occurred while trying to retrive data from store'); },
onTimeOutCallback: function () { },
timeOut: 3 * 1000,
autoIncreaseTimeOut: 1000,
retryOnTimeOut: false,
loadingButtonText: 'Loading...',
loadMoreButtonText: 'Load more',
fullListText: 'There is no more items to show',
routValues: null
I tried this, but leads to an error:
$.jScroller.defaults.extraParams = val;
Upvotes: 2
Views: 464
Reputation: 171669
Here are 2 very simple plugins. Neither has any defaults set, yet both respond to options being passed into them. One uses $.fn.plugin.defaults
to set the defaults, the other uses a local var
as you have started. To a certain degree it is a matter of personal preference along with complexity of plugin as to which way you set defaults.
Note that options are being set externally on plugin #2 two different ways
DEMO: http://jsfiddle.net/fCbm8/1
(function($) {
$.fn.plugin_1 = function(options) {
var defaults = {}; /* merge the options into defaults*/
var opts = $.extend({}, defaults, options);
return this.each(function() {
if (opts.green) {
$(this).css('background', 'green')
}
});
}
})(jQuery);
(function($) {
$.fn.plugin_2 = function(options) { /* merge the options into defaults*/
var opts = $.extend({}, $.fn.plugin_2.defaults, options);
return this.each(function() {
if (opts.big) {
$(this).css('font-size', '30px')
}
if (opts.color) {
$(this).css('color', 'white')
}
});
}
$.fn.plugin_2.defaults = {};
})(jQuery)
$(function() {
$.fn.plugin_2.defaults.big = true;
$('div').plugin_2({color:true}).plugin_1({green: true })
})
Upvotes: 2
Reputation: 9847
From the manual:
For more complex and customizable plugins that provide many options, it's a best practice to have default settings that can get extended (using
$.extend
) when the plugin is invoked. So instead of calling a plugin with a large number of arguments, you can call it with one argument which is an object literal of the settings you would like to override.
$.fn.tooltip = function( options ) {
// Create some defaults, extending them with any options that were provided
var settings = $.extend( {
'location' : 'top',
'background-color' : 'blue'
}, options);
return this.each(function() {
// Tooltip plugin code here
});
};
})( jQuery );
In the example, the manual shows how you can call the plugin by passing extra parameters, overriding the default ones if you wish to (like {location: left}
).
Upvotes: 1