My favorite jQuery plug-in template and jquery Plug-In Template
I have been using jQuery for a long time, and I will often write some plug-ins for it ). I tried to write in different ways. Now this template is my favorite one:
123456789101112131415161718192021222324252627282930313233 |
;( function ($) { // multiple plugins can go here ( function (pluginName) { var defaults = { color: 'black' , testFor: function (div) { return true ; } }; $.fn[pluginName] = function (options) { options = $.extend( true , {}, defaults, options); return this .each( function () { var elem = this , $elem = $(elem); // heres the guts of the plugin if (options.testFor(elem)) { $elem.css({ borderWidth: 1, borderStyle: 'solid' , borderColor: options.color }); } }); }; $.fn[pluginName].defaults = defaults; })( 'borderize' ); })(jQuery); // Usage $( 'div' ).borderize(); $( 'div' ).borderize({color: 'red' }); |
The following are the reasons why I like this template:
1. You can still access the default options, even if it is overwritten (simply access through the parent attribute)
2. Modify pluginName to change the plug-in name. (This method is also very beneficial to code compression)
Point #1 is very powerful. For example, we want to repeat this method, but we still want to retain the original method. Let's look at the example below:
12345678910111213141516171819 |
$( '.borderize' ).borderize({ testFor: function (elem) { var $elem = $(elem); if (elem.is( '.inactive' )) { return false ; } else { // calling "parent" function return $.fn.borderize.defaults.testFor.apply( this , arguments); } } }); We can even do this with regular properties like this var someVarThatMayBeSet = false ; /* code ... */ $( '.borderize' ).borderize({ color: someVarThatMayBeSet ? 'red' : $.fn.borderize.defaults.color }); |
Do you have a better template? Please reply.
Original article kolodny. github. io