In this article I show you my pattern to create jQuery plugins.
I develop jQuery plugins from long time and I tried different way to do it. When I found this pattern I use it every time I need to do complex functions.
jQuery plugin pattern code
Here is the code:
/*
Name: jQueryPluginPattern
File: jQueryPluginPattern.js
Author: Luca Dioli
*/
(function ($) {
jQuery.fn.jQueryPluginPattern = function (options) {
var opts = $.extend({}, $().jQueryPluginPattern.defaults, options);
var obj = $(this);
function init() {
obj.append('init()<br />');
obj.append('- param1: '+opts.param1+'<br />');
obj.append('- param2: '+opts.param2+'<br />');
privateFunction();
}
function privateFunction(){
obj.append('Private function<br />');
}
this.publicFunction = function (){
obj.append('Public function<br />');
}
init();
return this;
};
jQuery.fn.jQueryPluginPattern.defaults = {
param1: 'value1',
param2: 'value2'
};
})(jQuery);
How to call it
<script type="text/javascript">
var example = $('span').jQueryPluginPattern({param1: 'newValue'});
example.publicFunction();
</script>
Some explanations
- $(this): is the element assigned to the function, in this case “$(‘span’)”. If the function is called in this way: “$().jQueryPluginPattern()”, “$(this)” would be empty.
- $().jQueryPluginPattern.defaults: in this object there are the default options that are extended in the beginning of the function.
- privateFunction(): this is a private function that can be called only inside the plugin.
- publicFunction(): this is a public function that can be called from outside the plugin.
- return this;: with this instruction is possible to create a variable with the plugin object when it is declared. This can be avoid if you don’t need it.
- $(this): is the element assigned to the function, in this case “$(‘span’)”. If the function is called in this way: “$().jQueryPluginPattern()”, “$(this)” would be empty.
- $().jQueryPluginPattern.defaults: in this object there are the default options that are extended in the beginning of the function.
- privateFunction(): this is a private function that can be called only inside the plugin.
- publicFunction(): this is a public function that can be called from outside the plugin.
- return this;: with this instruction is possible to create a variable with the plugin object when it is declared. This can be avoid if you don’t need it.
I need to say you a BIG THANK YOU! I tried everything starting from Smashing Magazine to 30 links from google… But this is what I want! A plugin template with CLEAR structure, with both of public and private methods… Great job