jQuery插件開發--(轉)


1,開始

可以通過為jQuery.fn增加一個新的函數來編寫jQuery插件。屬性的名字就是你的插件的名字:

 

Js代碼    收藏代碼
  1. jQuery.fn.myPlugin = function(){  
  2.     //開始寫你的代碼吧!  
  3. };  

 

 但是,那惹人喜愛的美元符號$哪里去了?她就是jQuery,但是為了確保你的插件與其他使用$的庫不沖突,最好使用一個立即執行的匿名函數,這個匿名函數的參數是jQuery,這樣其他的庫就可以放心的使用$符號了。

 

Js代碼    收藏代碼
  1. (function( $ ){  
  2.   $.fn.myPlugin = function() {  
  3.     
  4.     // 開始吧!  
  5.   
  6.   };  
  7. })( jQuery );  

 

 這樣更好了就。在閉包內,可以放心的使用$符號了~

2,上下文

現在已經可以編寫我們的代碼了,但是編寫之前,我必須說一說上下文。在插件內部的范圍中,this關鍵字指向的是jQuery對象。人們很容易誤解這一點,因為在正常使用jQuery的時候,this通常指向的是一個DOM元素。不了解這一點,會經常使用$又包裝了一次。

 

Js代碼    收藏代碼
  1. (function( $ ){  
  2.   
  3.   $.fn.myPlugin = function() {  
  4.     
  5.     // 沒有必要使用$(this)  
  6.   
  7.     // $(this) 跟 $($('#element'))是一樣的  
  8.           
  9.     this.fadeIn('normal'function(){  
  10.   
  11.       //這里的this指的就是一個DOM元素了  
  12.   
  13.     });  
  14.   
  15.   };  
  16. })( jQuery );  
  17.   
  18. $('#element').myPlugin();  

 

3,基本開發 

接下來寫一個能用的插件吧。

 

Js代碼    收藏代碼
  1. (function( $ ){  
  2.   
  3.   $.fn.maxHeight = function() {  
  4.     
  5.     var max = 0;  
  6.   
  7.     this.each(function() {  
  8.       max = Math.max( max, $(this).height() );  
  9.     });  
  10.   
  11.     return max;  
  12.   };  
  13. })( jQuery );  
Js代碼    收藏代碼
  1. var tallest = $('div').maxHeight();  

 

 這是一個簡單的插件,通過調用height()返回頁面上height最大的div的height。

4,維護鏈式開發的特性

上一個例子是返回了一個整數,但是大多數情況下,一個插件緊緊是修改收集到的元素,然后返回這個元素讓鏈條上的下一個使用。這是jQuery設計的精美之處,也是jQuery如此流行的原因之一。為了保證可鏈式,你必須返回this。

 

Js代碼    收藏代碼
  1. (function( $ ){  
  2.   
  3.   $.fn.lockDimensions = function( type ) {    
  4.   
  5.     return this.each(function() {  
  6.   
  7.       var $this = $(this);  
  8.   
  9.       if ( !type || type == 'width' ) {  
  10.         $this.width( $this.width() );  
  11.       }  
  12.   
  13.       if ( !type || type == 'height' ) {  
  14.         $this.height( $this.height() );  
  15.       }  
  16.   
  17.     });  
  18.   
  19.   };  
  20. })( jQuery );  
Js代碼    收藏代碼
  1. $('div').lockDimensions('width').css('color','red');  

 

 因為該插件返回了this,所以保證了可鏈式,從而可以繼續使用jQuery方法進行修改,如css()。如果你的插件如果不是返回一個簡單值,你通常應該返回this。而且,正如你可能想到的,你傳進去的參數也可以在你的插件中訪問。所以在這個例子中,可以訪問到type。

5,默認值和選項

為了一些復雜的,可訂制的插件,最好提供一套默認值,在被調用的時候擴展默認值。這樣,調用函數的時候就不用傳入一大堆參數,而是傳入需要被替換的參數。你可以這樣做:

 

Js代碼    收藏代碼
  1. (function( $ ){  
  2.   
  3.   $.fn.tooltip = function( options ) {    
  4.   
  5.     var settings = {  
  6.       'location'         : 'top',  
  7.       'background-color' : 'blue'  
  8.     };  
  9.   
  10.     return this.each(function() {          
  11.       // 如果存在選項,則合並之  
  12.       if ( options ) {   
  13.         $.extend( settings, options );  
  14.       }  
  15.   
  16.       // 其他代碼咯  
  17.   
  18.     });  
  19.   
  20.   };  
  21. })( jQuery );  
Js代碼    收藏代碼
  1. $('div').tooltip({'location':'left'});  

 

 在這個例子中,調用插件后,默認的location會被替換城'left',而background-color還是'blue'。這樣可以保證高度可配置性,而不需要開發者定義所有可能的選項了。

6,命名空間

正確的命名空間對於插件開發十分重要,這樣能確保你的插件不被其他插件重寫,也能避免被頁面上其他代碼重寫。命名空間可以使你更長壽,因為你能記錄你自己的方法,事件,數據等。

a,插件方法

在任何情況下,都不要在一個插件中為jQuery.fn增加多個方法。如:

 

Js代碼    收藏代碼
  1. (function( $ ){  
  2.   
  3.   $.fn.tooltip = function( options ) { // 這樣 };  
  4.   $.fn.tooltipShow = function( ) { // 是   };  
  5.   $.fn.tooltipHide = function( ) { // 不好的  };  
  6.   $.fn.tooltipUpdate = function( content ) { // 同學!  };  
  7.   
  8. })( jQuery );  

 

 不推薦這樣使用,搞亂了$.fn命名空間。要糾正之,你可以把所有的方法放進一個對象中,然后通過不同的參數來調用。

 

Js代碼    收藏代碼
  1. (function( $ ){  
  2.   
  3.   var methods = {  
  4.     init : function( options ) { // THIS },  
  5.     show : function( ) { // IS   },  
  6.     hide : function( ) { // GOOD },  
  7.     update : function( content ) { // !!! }  
  8.   };  
  9.   
  10.   $.fn.tooltip = function( method ) {  
  11.       
  12.     // Method calling logic  
  13.     if ( methods[method] ) {  
  14.       return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));  
  15.     } else if ( typeof method === 'object' || ! method ) {  
  16.       return methods.init.apply( this, arguments );  
  17.     } else {  
  18.       $.error( 'Method ' +  method + ' does not exist on jQuery.tooltip' );  
  19.     }      
  20.     
  21.   };  
  22.   
  23. })( jQuery );  

 

Js代碼    收藏代碼
  1. $('div').tooltip({  // calls the init method  
  2.   foo : 'bar'  
  3. });  
  4. $('div').tooltip('hide'); // calls the hide method  
  5. $('div').tooltip('update''This is the new tooltip content!'); // calls the update method  

jQuery自己的擴展也是使用這種插件結構。

b,事件

綁定事件的命名空間是比較不為人知的。如果你的插件綁定了某個事件,最好將它搞到一個命名空間中。這樣,如果你以后需要解綁,就不會影響到其他綁定到這個事件上的函數了。你可以使用".<namespace>"來增加命名空間。

 

Js代碼    收藏代碼
  1. (function( $ ){  
  2.   
  3.   var methods = {  
  4.      init : function( options ) {  
  5.   
  6.        return this.each(function(){  
  7.          $(window).bind('resize.tooltip', methods.reposition);  
  8.        });  
  9.   
  10.      },  
  11.      destroy : function( ) {  
  12.   
  13.        return this.each(function(){  
  14.          $(window).unbind('.tooltip');  
  15.        })  
  16.   
  17.      },  
  18.      reposition : function( ) { // ... },  
  19.      show : function( ) { // ... },  
  20.      hide : function( ) { // ... },  
  21.      update : function( content ) { // ...}  
  22.   };  
  23.   
  24.   $.fn.tooltip = function( method ) {  
  25.       
  26.     if ( methods[method] ) {  
  27.       return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));  
  28.     } else if ( typeof method === 'object' || ! method ) {  
  29.       return methods.init.apply( this, arguments );  
  30.     } else {  
  31.       $.error( 'Method ' +  method + ' does not exist on jQuery.tooltip' );  
  32.     }      
  33.     
  34.   };  
  35.   
  36. })( jQuery );  
  37.   
  38. $('#fun').tooltip();  
  39. // Some time later...  
  40. $('#fun').tooltip('destroy');  

 

 

在這個例子中,tooltip在init方法中初始化,它將reposition方法綁定到window對象的resize事件的tooltip名字空間下。稍候,如果開發者需要去掉這個tooltip,我們可以解綁這個綁定。這樣就不會影響到其他綁定到window對象的resize事件的方法了。

c,數據

在開發插件的時候,你通常會有保持狀態或者檢查你的插件是否已經初始化的需要。使用jQuery的data方法是保持變量的很好的方法。但是,我們不把變量單獨保存,而是放在一個對象中,這樣就可以在一個名字空間下統一訪問了。

 

Js代碼    收藏代碼
  1. (function( $ ){  
  2.   
  3.   var methods = {  
  4.      init : function( options ) {  
  5.   
  6.        return this.each(function(){  
  7.            
  8.          var $this = $(this),  
  9.              data = $this.data('tooltip'),  
  10.              tooltip = $('<div />', {  
  11.                text : $this.attr('title')  
  12.              });  
  13.            
  14.          // If the plugin hasn't been initialized yet  
  15.          if ( ! data ) {  
  16.            
  17.            /* 
  18.              Do more setup stuff here 
  19.            */  
  20.   
  21.            $(this).data('tooltip', {  
  22.                target : $this,  
  23.                tooltip : tooltip  
  24.            });  
  25.   
  26.          }  
  27.        });  
  28.      },  
  29.      destroy : function( ) {  
  30.   
  31.        return this.each(function(){  
  32.   
  33.          var $this = $(this),  
  34.              data = $this.data('tooltip');  
  35.   
  36.          // Namespacing FTW  
  37.          $(window).unbind('.tooltip');  
  38.          data.tooltip.remove();  
  39.          $this.removeData('tooltip');  
  40.   
  41.        })  
  42.   
  43.      },  
  44.      reposition : function( ) { // ... },  
  45.      show : function( ) { // ... },  
  46.      hide : function( ) { // ... },  
  47.      update : function( content ) { // ...}  
  48.   };  
  49.   
  50.   $.fn.tooltip = function( method ) {  
  51.       
  52.     if ( methods[method] ) {  
  53.       return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));  
  54.     } else if ( typeof method === 'object' || ! method ) {  
  55.       return methods.init.apply( this, arguments );  
  56.     } else {  
  57.       $.error( 'Method ' +  method + ' does not exist on jQuery.tooltip' );  
  58.     }      
  59.     
  60.   };  
  61.   
  62. })( jQuery );  

 

 使用data方法可以幫助你在插件的各個方法間保持變量和狀態。將各種變量放在一個對象中,可以方便訪問,也可以方便移除。

7,總結與最佳實踐

編寫jQuery插件可以充分利用庫,將公用的函數抽象出來,“循環利用”。以下是簡短的總結:

 

  • 使用(function($){//plugin})(jQuery);來包裝你的插件
  • 不要在插件的初始范圍中重復包裹
  • 除非你返回原始值,否則返回this指針來保證可鏈式
  • 不要用一串參數,而是使用一個對象,並且設置默認值
  • 一個插件,不要為jQuery.fn附上多個函數
  • 為你的函數,事件,數據附着到某個命名空間


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM