一、靜態方法和擴展插件(類級別組件和對象級別組件)
1、即是給jQuery命名空間下添加新的全局函數,也稱為靜態方法。如$.Ajax()
, $.extend()
就是采用的類級別組件開發;
jQuery.pluginName = function() { // code };
2、對象級別的組件開發指的是直接在jQuery原型上掛載的方法,這樣可以通過選擇器獲取的jQuery對象實例也能共享改方法,稱為動態方法;
$.fn.pluginName = function() { // code };
3、考慮到環境的完整例子;通過閉包將jQuery對象傳入。
(function ($) { $.fn.myPlugin = function () { //此處沒有必要將this包在$號中如$(this),因為this已經是一個jQuery對象。 //$(this)等同於 $($('#element')); this.fadeIn('normal', function () { //此處callback函數中this關鍵字代表一個DOM元素 }); }; })(jQuery); $('#element').myPlugin();
二、維護Chainability
1、維護Chainability指的是維護通過返回this關鍵字,從而維護鏈式調用的寫法。
(function ($) { $.fn.lockDimensions = function (type) { return this.each(function () { //這里面寫什么不重要,重要的是,return this返回的jquery dom對象維護了后面調用時還能繼續調用jq的其他方法,如:css()方法 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');
三、設置默認值
1、設置默認值指的是對於比較復雜的和提供了許多選項可定制的的插件,最好有一個當插件被調用的時候可以被拓展的默認設置(通過使用$.extend)。 因此,相對於調用一個有大量參數的插件,你可以調用一個對象參數,包含你了你想覆寫的設置。
(function ($) { $.fn.tooltip = function (options) { //創建一些默認值,拓展任何被提供的選項 var settings = $.extend({ 'location': 'top', 'background-color': 'blue' }, options); return this.each(function () { // Tooltip插件代碼 }); }; })(jQuery); $('div').tooltip({ 'location': 'left' });
四、命名空間與插件方法
1、命名空間與固定方法:正確命名空間你的插件是插件開發的一個非常重要的一部分。 正確的命名空間,可以保證你的插件將有一個非常低的機會被其他插件或同一頁上的其他代碼覆蓋。 命名空間也使得你的生活作為一個插件開發人員更容易,因為它可以幫助你更好地跟蹤你的方法,事件和數據。
(function ($) { var methods = { init: function (options) { // this }, show: function () { // is }, hide: function () { // good }, 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); //調用init方法 $('div').tooltip(); //調用init方法 $('div').tooltip({ foo: 'bar' }); // 調用hide方法 $('div').tooltip('hide'); //調用Update方法 $('div').tooltip('update', 'This is the new tooltip content!');
這里通過傳入方法名字符串及參數,從而調用它們
五、總結
- 不要冗余包裹this關鍵字在插件的功能范圍內。
- 除非插件返回特定值,否則總是返回this關鍵字來維持chainability 。
- 傳遞一個可拓展的默認對象參數而不是大量的參數給插件。
- 不要在一個插件中多次命名不同方法。
- 始終命名空間的方法,事件和數據。