2012-01-14 55 views
0

我只是想知道如果下面的方法是一個很好的建立一個jQuery插件,如果沒有這是最好的做法:這種方式是構建插件的好方法嗎?

$.fn.loginsys = function(options) { 

    var opts = $.extend({}, $.fn.loginsys.defaults, options); 

    return this.each(function() { 

     /* Code To Be Executed */ 

    }); 

} 

$.fn.loginsys.defaults = { 

    /* Some Options */ 

} 
+0

您是否希望用戶能夠更改默認選項? – pimvdb 2012-01-14 22:43:26

+0

是的,我確實需要這個。 – Roland 2012-01-14 23:13:56

回答

0

我會suggestm這從jQuery的教程插件(但有幾個方法) :

(function($) 
{ 
    var globalSettings= 
    { 
     width:400, 
     height:400 
    }; 

    var methods = 
    { 
     init : function(options) 
     { 
      return this.each(function() 
      { 
       var $this=$(this); 
       var settings=$.extend({}, globalSettings, options); 

       //your code 

      }); 
     }, 
     destroy : function() 
     { 
      return this.each(function() 
      { 

      }); 
     }, 
     option : function(option, value) 
     { 

      if(value!=null && value!=undefined) 
      { 
       return this.each(function(){ 
        var $this=$(this); 
        var curr_setts=$this.data('settings'); 
        curr_setts[option]=value; 
        $this.data('settings',curr_setts); 
       }); 
      } 
      else 
      { 
       var $this=$(this); 
       var curr_setts=$this.data('settings'); 
       return curr_setts[option]; 
      } 
     } 
    }; 

    $.fn.siter=function(method, options) 
    { 
     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'); 
     } 
    }; 

})(jQuery); 
+1

切勿使用換行符來避免自動插入分號( - >提前終止多行語句/聲明)。另外,它很醜陋。 – Flo 2012-01-14 22:54:36

+0

你真的很老,有幾種編寫代碼的方式,在我看來,這是最可讀的方式。它也有一個特定的名字 – albanx 2012-01-14 23:34:47

+0

我有一個關於這種編寫插件的方式的問題,我在其他插件中發現了像這樣的'jQuery.fn.reverse = Array.prototype.reverse;'在它的開始處,是什麼那代表什麼? – Roland 2012-01-14 23:51:57

1

最佳實踐,一切都拋開,是有希望揭露一個理由默認設置?

如果您希望它們可以從外部進行編輯,您可能需要公開一個setter,並將它們放在$ .fn.loginsys = function閉包中,以確保它們不會被弄亂以某種方式阻止你的插件工作。

請參閱jQuery的ajaxSettings()例如。

+0

這似乎是一個好主意,是@albanx代碼示例一個好主意,可以選項在插件之外編輯? – Roland 2012-01-14 23:18:00

1

我認爲你只是缺少包裝

(function($) { 

    // plugin code here 

})(jQuery); 

但是,也有很多插件的模式在那裏;這裏有一個bunch of templates可供下載。

+0

謝謝,我會看看所有的模板:) – Roland 2012-01-14 23:43:34

相關問題