我最喜欢的jQuery插件模板

本文介绍了一种作者常用的jQuery插件编写模板,该模板通过闭包保护默认配置,并允许覆盖默认行为同时保持对原始功能的访问。此外,还展示了如何根据不同条件定制插件的行为。

  我使用jQuery已经有相当长的时间了,并且我会常常为它写一些插件(plugin)。我尝试过用不同的方式去写,现在这个模板是我最喜欢的:

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
;( 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' });

  以下是我喜欢这种模板的原因

  1. 你仍然可以访问里面的默认选项,即便它被重写了(简单地通过父属性的访问)

  2. 通过修改pluginName即可更改插件的名字。(这种方式对代码压缩也非常有利)

  第#1点非常强大,比如说我们希望复写这个方法,但是仍然希望保留原来的方法,我们可以看下面的例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
$( '.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
});

  你有更好的模板吗?欢迎回复。

  原文 kolodny.github.io

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值