Reputation: 3204
For some reason I can only find plugin examples that are directly bound to an existing element like $(selector).myPlugin();
What I want to be able to do is quite simply just call new myPlugin() with options.
new myPlugin({
'option1': 'option 1 value',
'option2': 'option 2 value',
'option3': 'option 3 value',
'option4': 'option 4 value'
});
I have a regular function that has up to 8 parameters, but I don't always need to define them all and I hate having to include the defaults for all of the parameters I don't need to define.
function myFunction(param1, param2, param3, param4, param5, param6, param7, param8){
// Operations here
}
Sometimes I only need to define the first and fifth parameters or whatever and I need defaults for the rest. This is a pain.
Maybe I've missed an example like this here in my searches.
Upvotes: 4
Views: 1291
Reputation: 173552
You can just use the $
namespace to declare your new function and use $.extend()
to handle your defaults:
(function($) {
var defaults = {
name: 'Jack',
number: '555-jack'
}
$.myPlugin = function(options) {
var settings = $.extend({}, defaults, options);
this.someFunction = function() {
// you can use settings here
}
}
}(jQuery));
I'm defining the defaults as a private variable (outside code can't access it) and use it inside the myPlugin
constructor. An example how the call works:
var x = new $.myPlugin({
number: '666-something'
});
Inside the constructor, the settings
variable contains the name from defaults
and the number from the constructor arguments.
Upvotes: 5
Reputation: 114347
You can pass arrays or JSON as a single parameter to your function instead of individual values.
Upvotes: 0