Javascript 插件统一的实现步骤

 步骤:

1     // 1. 定义立即调用的函数
2 +function($){
3     "use strict";      //使用严格模式ES5支持
4      //后续步骤
5      // 2. xx 插件类及原型方法的定义 
6      // 3. 在jQuery上定义xx插件,并重设插件构造器
7      // 4. 防冲突处理
8      // 5. 绑定触发事件
9 }(window.jQuery)

 

代码例子(bootstrap的alert.js):

 1 /* ========================================================================
 2  * Bootstrap: alert.js v3.2.0
 3  * http://getbootstrap.com/javascript/#alerts
 4  * ========================================================================
 5  * Copyright 2011-2014 Twitter, Inc.
 6  * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
 7  * ======================================================================== */
 8 
 9 
10 +function ($) {
11   'use strict';
12 
13   // ALERT CLASS DEFINITION
14   // ======================
15 
16   var dismiss = '[data-dismiss="alert"]'
17   var Alert   = function (el) {
18     $(el).on('click', dismiss, this.close)
19   }
20 
21   Alert.VERSION = '3.2.0'
22 
23   Alert.prototype.close = function (e) {
24     var $this    = $(this)
25     var selector = $this.attr('data-target')
26 
27     if (!selector) {
28       selector = $this.attr('href')
29       selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7
30     }
31 
32     var $parent = $(selector)
33 
34     if (e) e.preventDefault()
35 
36     if (!$parent.length) {
37       $parent = $this.hasClass('alert') ? $this : $this.parent()
38     }
39 
40     $parent.trigger(e = $.Event('close.bs.alert'))
41 
42     if (e.isDefaultPrevented()) return
43 
44     $parent.removeClass('in')
45 
46     function removeElement() {
47       // detach from parent, fire event then clean up data
48       $parent.detach().trigger('closed.bs.alert').remove()
49     }
50 
51     $.support.transition && $parent.hasClass('fade') ?
52       $parent
53         .one('bsTransitionEnd', removeElement)
54         .emulateTransitionEnd(150) :
55       removeElement()
56   }
57 
58 
59   // ALERT PLUGIN DEFINITION
60   // =======================
61 
62   function Plugin(option) {
63     return this.each(function () {
64       var $this = $(this)
65       var data  = $this.data('bs.alert')
66 
67       if (!data) $this.data('bs.alert', (data = new Alert(this)))
68       if (typeof option == 'string') data[option].call($this)
69     })
70   }
71 
72   var old = $.fn.alert
73 
74   $.fn.alert             = Plugin
75   $.fn.alert.Constructor = Alert
76 
77 
78   // ALERT NO CONFLICT
79   // =================
80 
81   $.fn.alert.noConflict = function () {
82     $.fn.alert = old
83     return this
84   }
85 
86 
87   // ALERT DATA-API
88   // ==============
89 
90   $(document).on('click.bs.alert.data-api', dismiss, Alert.prototype.close)
91 
92 }(jQuery);

 

posted @ 2014-10-27 20:51  mushishi  阅读(288)  评论(0)    收藏  举报