Один из вариантов - начать с шаблона, подобного следующему, который заботится о расширении набора значений по умолчанию параметрами, с которыми была вызвана функция:
// start of anonymous function, no global namespace is used. Formal parameter $ is passed the jQuery object, see closing of function definition.
(function ($) {
// define default parameters for myPlugin. These can be overridden by the call, or from data attached to the jQuery object
var defaults = {optionOne: true, optionTwo: 'CALI', callback: function () {/* code here, or leave it out of the defaults so it will be null by default */}};
// this next line adds myPlugin to the jQuery functions because ".fn" is an alias for "prototype". The function call enables behavior like $("selector").myPlugin('action', {optionOne: false});
$.fn.myPlugin = function (action, options) {
var passed = options, // passed will store the options that were passed in. This allows us to see what was sent after the options are expanded with defaults.
obj, // the jQuery object being worked with -- check to see if this can be handled with "el" locally.
dataStore, // object to store persistant data for the jQuery objects being worked with.
result; // used if we are passed a call that requires returning a result rather than returning the jQuery collection we were passed.
// code here, functions to be called as actions
function initialize() {} function single() {} function getDual() {} function setDual() {}
function getOptions(el) {
var optionsPrior = el.data('myPlugin:options'), // attempt to load prior settings
dataStorePrior = el.data('myPlugin:data'); // load any stored data
options = (optionsPrior !== undefined) ? optionsPrior : $.extend(true, {}, defaults, options); // sets options either to prior options or extends the default options with those that were passed in.
options = $.metadata ? $.extend(true, {}, options, el.metadata()) : options; // check for settings attached to the current object
if (dataStorePrior !== undefined) { // if there is a prior data store populate the active datastore with it.
dataStore = dataStorePrior;
}
}
function setOptions(el) {
el.data('myPlugin:options', options); // store setting to the object
el.data('myPlugin:data', dataStore); // store datastore to the object
}
// check to see if the first parameter passed is an object instead of an string containing an action, if so then use the object as options and set the action to initalize.
if (!action || typeof (action) === 'object') {
options = action;
action = 'initialize';
}
// process each element in the jQuery object collection
this.each(function (el) {
// store reference to the currently processing jQuery object -- check to see the value of this over using "el" from the function
var obj = $(this);
getOptions(obj); // load the current options
if (action && typeof (action) === 'string') { // this is an alternative to the use of "var methods = {function methodOne ()..." that allows a single action to have both a set and get that can call different functions.
switch (action) {
case 'initialize':
initialize(obj);
break;
case 'singleOptionAction':
single(obj);
break;
case 'dualModeAction':
//return and set
if (passed === undefined) {
result = getDual;
} else {
setDual(obj, passed);
}
break;
default:
break; // we have no listed method that matched what they sent
}
}
setOptions(el);
// code here
});
return this; // this enables chaining; without it the jQuery collection that is passed in is not passed further along the chain. Alternatively if you are trying to filter or modify the jQuery collection you'll want to return a modified version of this.
};
}(jQuery)); // end anonymous function definition and execute it, passing in the jQuery object.
// jQuery should already be loaded, and the "$" reference is used only within your function definition, keeping this reference safe from being clobbered by other scripts.
// After execution, your plugin is defined and ready to use.
Существует множество способов написания плагина jQuery, и в этом примере показан только один набор вариантов.