Wanting a quick way to create a plugin in jQuery I found A Plugin Development Pattern (Learning jQuery), by Mike Alsup, via Improving upon the jQuery Plugin Template (Google Groups). Later, much later, I looked in the more obvious place; Plugins/Authoring (jQuery). I work best from hacking examples, so Mike Alsup’s pattern/template was the most useful to me.
The only difference between the following template and Mike Alsup’s is that I’ve stripped it down to just the essentials.
The template
(function($)
{
$.fn.plugin = function(options)
{
// Set the options.
options = $.extend({}, $.fn.plugin.defaults, options);
// Go through the matched elements and return the jQuery object.
return this.each(function()
{
});
};
// Public defaults.
$.fn.plugin.defaults = {
property: 'value'
};
// Private functions.
function func()
{
return;
};
// Public functions.
$.fn.plugin.func = function()
{
return;
};
})(jQuery);
Updates
- Removed “var” where not required, many thanks to Jim (Jim’s comment)
Thanks for this.
The “var” there is not required, as options is already a local variable by virtue of being an argument.
Did you find a way to have acces to the selector inside $.fn.plugin.func in case of $(“#foo”).plugin.func;?
Hi Dykam
No, because essentially we’re just accessing the plugin object (passing nothing to it) and then calling the function on that object. The problem, to a certain degree, is about namespacing the plugin, so what if we just create a “sub-plugin” like as follows:
$.fn.plugin_func = function() {}
and call it with $(‘#foo’).plugin_func();
Basically it is just another plugin, but by name (only) related to the main plugin. You could still access the main plugin objects etc. from the “sub-plugin”. For example getting the defaults = $.fn.plugin.defaults.
I’ve not done a plugin that works like I’m describing and so I have no idea of the problems involved in working across plugins. If you do try it out, please let me know how you get on. Good luck!