jQuery外掛程式的編寫相關技術 設計總結和最佳實務

來源:互聯網
上載者:User

標籤:des   blog   http   io   color   ar   os   使用   sp   

原文:http://www.itzhai.com/jquery-plug-in-the-preparation-of-related-technical-design-summary-and-best-practices.html1、聲明外掛程式名稱:

添加一個函數到jQuery.fn(jQuery.prototype)對象,該函數的名稱就是你的外掛程式名稱:

jQuery.fn.myPlugin = function() {  // Do your awesome plugin stuff here};

在命名不與jQuery其他函數衝突的情況,可以使用閉包的方式使用$符號:

(function( $ ) {  $.fn.myPlugin = function() {    // Do your awesome plugin stuff here  };})( jQuery );
2、外掛程式中的上下文:

jQuery接收一個回調,該回調本身就指向了dom,直接使用this就相當於我們平時的$(this)的情況:

(function( $ ){  $.fn.myPlugin = function() {    // there‘s no need to do $(this) because    // "this" is already a jquery object    // $(this) would be the same as $($(‘#element‘));    this.fadeIn(‘normal‘, function(){ // the this keyword is a DOM element }); };})( jQuery );$(‘#element‘).myPlugin();

下面是一個簡單的jQuery外掛程式,實現擷取所有div的最大高度:

(function( $ ){  $.fn.maxHeight = function() {    var max = 0;    this.each(function() {      max = Math.max( max, $(this).height() ); }); return max; };})( jQuery );var tallest = $(‘div‘).maxHeight(); // Returns the height of the tallest div
3、維護連結性:

前面的樣本返回一個整數值最高的div,但是通常的意圖僅在某種程度上是僅修改外掛程式的元素集合,並將它們傳遞到下一個鏈中的方法。這樣的jQuery的設計優雅的地方。所以保持連結性放到一個外掛程式,您必須確保您的外掛程式返回這個關鍵字。

(function( $ ){  $.fn.lockDimensions = function( type ) {      return this.each(function() {      var $this = $(this); if ( !type || type == ‘width‘ ) { $this.width( $this.width() ); } if ( !type || type == ‘height‘ ) { $this.height( $this.height() ); } }); };})( jQuery );$(‘div‘).lockDimensions(‘width‘).css(‘color‘, ‘red‘);

因為外掛程式返回this關鍵字的範圍,它維護連結性,jQuery可以繼續利用jQuery方法,如. css。所以,如果你的外掛程式不返回一個內在價值,你應該總是返回this。

4、參數的傳遞,Defaults和Options:
(function( $ ){  $.fn.tooltip = function( options ) {      // Create some defaults, extending them with any options that were provided    var settings = $.extend( {      ‘location‘         : ‘top‘, ‘background-color‘ : ‘blue‘ }, options); return this.each(function() { // Tooltip plugin code here }); };})( jQuery );$(‘div‘).tooltip({ ‘location‘ : ‘left‘});

通過$.extend合并預設參數和調用者傳入的參數。

5、命名空間:

正確的命名空間在外掛程式開發中是一個非常重要的部分。正確的命名空間,可以確保你的外掛程式將有一個很低的幾率在同一個頁面上被他外掛程式或代碼覆蓋。

在任何情況下都不應該在一個外掛程式的jQuery.fn對象中聲稱多個名稱空間。

(function( $ ){  $.fn.tooltip = function( options ) {     // THIS  };  $.fn.tooltipShow = function( ) {    // IS  };  $.fn.tooltipHide = function( ) { // BAD }; $.fn.tooltipUpdate = function( content ) { // !!! };})( jQuery );

你應該收集所有的方法到一個對象化字面,並且通過方法的字面值進行調用:

(function( $ ){  var methods = {    init : function( options ) {       // THIS     },    show : function( ) {      // IS }, hide : function( ) { // GOOD }, update : function( content ) { // !!! } }; $.fn.tooltip = function( method ) { // Method calling logic if ( methods[method] ) { return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 )); } else if ( typeof method === ‘object‘ || ! method ) { return methods.init.apply( this, arguments ); } else { $.error( ‘Method ‘ + method + ‘ does not exist on jQuery.tooltip‘ ); } };})( jQuery );// calls the init method$(‘div‘).tooltip(); // calls the init method$(‘div‘).tooltip({ foo : ‘bar‘});// calls the hide method$(‘div‘).tooltip(‘hide‘); // calls the update method$(‘div‘).tooltip(‘update‘, ‘This is the new tooltip content!‘);

這種類型的方法封裝和體繫結構在jQuery外掛程式社區中是一個標準,它適用於無數的外掛程式,包括jQueryUI外掛程式和小組件。

6、Events:

Bind方法允許通過命名空間的方式綁定事件,如果你的外掛程式綁定了事件,可以通過命名空間的方式,在解除綁定事件時,你也可以這樣做,來防止影響到其他的事件。可以通過“.<namespace>” 的方式來設定綁定事件的命名空間。

(function( $ ){  var methods = {     init : function( options ) {       return this.each(function(){ $(window).bind(‘resize.tooltip‘, methods.reposition); }); }, destroy : function( ) { return this.each(function(){ $(window).unbind(‘.tooltip‘); }) }, reposition : function( ) { // ... }, show : function( ) { // ... }, hide : function( ) { // ... }, update : function( content ) { // ... } }; $.fn.tooltip = function( method ) { if ( methods[method] ) { return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 )); } else if ( typeof method === ‘object‘ || ! method ) { return methods.init.apply( this, arguments ); } else { $.error( ‘Method ‘ + method + ‘ does not exist on jQuery.tooltip‘ ); } };})( jQuery );$(‘#fun‘).tooltip();// Some time later...$(‘#fun‘).tooltip(‘destroy‘);
7、Data:

關於data方法可以參考官方的文檔:http://docs.jquery.com/Data,既是在頁面的元素中綁定儲存資料。

這裡通過編寫外掛程式,實現在頁面中的每個元素都綁定一些當前的狀態或者內容。

(function( $ ){  var methods = {     init : function( options ) {       return this.each(function(){ var $this = $(this), data = $this.data(‘tooltip‘), tooltip = $(‘<div />‘, { text : $this.attr(‘title‘) }); // If the plugin hasn‘t been initialized yet if ( ! data ) { /* Do more setup stuff here */ $(this).data(‘tooltip‘, { target : $this, tooltip : tooltip }); } }); }, destroy : function( ) { return this.each(function(){ var $this = $(this), data = $this.data(‘tooltip‘); // Namespacing FTW $(window).unbind(‘.tooltip‘); data.tooltip.remove(); $this.removeData(‘tooltip‘); }) }, reposition : function( ) { // ... }, show : function( ) { // ... }, hide : function( ) { // ... }, update : function( content ) { // ...} }; $.fn.tooltip = function( method ) { if ( methods[method] ) { return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 )); } else if ( typeof method === ‘object‘ || ! method ) { return methods.init.apply( this, arguments ); } else { $.error( ‘Method ‘ + method + ‘ does not exist on jQuery.tooltip‘ ); } };})( jQuery );
關於jQuery設計的總結和最佳實務:

編寫jQuery外掛程式允許您實現最大的類庫,抽象出你認為有用的功能和可重用的代碼,可以節省你的時間,使你的開發更加有效。記住當開發您的下一個jQuery外掛程式,可以遵循下面的一個簡短的總結:

1、 總是把你的外掛程式放入閉包中:

(function( $ ){ /* plugin goes here */ })( jQuery );

2、 在你的外掛程式直接範圍內,不要多餘的包裹住this關鍵字;

3、 除非你是從你的外掛程式中返回一個內在的值,一般都返回你的外掛程式的函數this關鍵字來維護連結性;

4、 與其傳入冗長的參數,不如通過你的外掛程式設定一個預設的參數,通過$.extend()方法進行擴充參數;

5、 不要在一個外掛程式中使用多個命名空間導致jQuery.fn對象變得很雜亂;

6、 總是為你的方法,事件和data建立命名空間。

關於具體的外掛程式開發說明,參考jQuery的官方文檔:

http://docs.jquery.com/Plugins/Authoring

jQuery外掛程式的編寫相關技術 設計總結和最佳實務

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.