I've been using jquery for quite a long time, and I will often write plugins (plugin) for it. I have tried different ways to write, now this template is my favorite:
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);
//下面是用法
$(
‘div‘
).borderize();
$(
‘div‘
).borderize({color:
‘red‘
});
|
Here's why I like this template
1. You can still access the default options inside, even if it is rewritten (simply by accessing the Parent property)
2. You can change the name of the plugin by modifying the pluginname. (This method is also very advantageous for code compression)
The first point is very powerful, for example, we want to replicate this method, but still want to retain the original method, we can look at the following example:
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? Welcome to reply.
Original Kolodny.github.io
My favorite jquery plugin template