One of the parameters to most jQuery plugins accepts an object as the argument, for example { option1: 'optionValue'}
. This allows the user to pass in whichever options that they want to change from the defaults. In most plugins, this options object is then merged with the default options using $.extend()
, overriding any of the default options with properties from the options object if they are defined.
One of the usual ways a plugin is written is as follows
(function($) {
$.fn.myPlugin = function(options) {
var settings = $.extend({ // these are the default properties
option1: 'default value',
option2: true,
option3: 5437
},
// merge with the options object passed in
// or an empty object
options || {});
// now we can use the settings object in our plugin, which will have
// property values from the settings object and the options object passed in
}
})(jQuery);
the options || {}
part in $.extend()
guards against a false value being passed for options
. The order of the objects in $.extend()
determines which properties take precendence- a property defined on an object will have it's value replaced (use the term roughly here) by the same property name declared on a later object.