jQuery插件和方法的作用是非常強大的,它可以節省大量開發時間。這篇文章将概述jQuery插件開發的基本知識,最佳做法和常見的陷阱。
入門
編寫一個jQuery插件開始于給jQuery.fn加入新的功能屬性,此處添加的對象屬性的名稱就是你插件的名稱:
jQuery.fn.myPlugin = function(){
//你自己的插件代碼
JavaScript庫沖突,我們最好将jQuery傳遞給一個自我執行的封閉程式,jQuery在此程式中映射為$符号,這樣可以避免$号被其他庫覆寫。
(function ($) {
$.fn.myPlugin = function () {
//你自己的插件代碼
在這個封閉程式中,我們可以無限制的使用$符号來表示jQuery函數。
環境
現在,我們可以開始編寫實際的插件代碼。 但是,在這之前,我們必須得對插件所處的環境有個概念。 在插件的範圍裡, this關鍵字代表了這個插件将要執行的jQuery對象, 這裡容易産生一個普遍的誤區,因為在其他包含callback的jQuery函數中,this關鍵字代表了原生的DOM元素。這常常會導緻開發者誤将this關鍵字無謂的包在jQuery中,如下所示。
(function ($) {
$.fn.myPlugin = function () {
//此處沒有必要将this包在$号中如$(this),因為this已經是一個jQuery對象。
//$(this)等同于 $($('#element'));
this.fadeIn('normal', function () {
//此處callback函數中this關鍵字代表一個DOM元素
});
};
})(jQuery);
$('#element').myPlugin();
基礎知識
現在,我們了解了jQuery插件的基礎知識,讓我們寫一個插件,做一些事情。
(function ($) {
$.fn.maxHeight = function () {
var max = 0;
this.each(function () {
max = Math.max(max, $(this).height());
});
return max;
};
})(jQuery);
var tallest = $('div').maxHeight(); //傳回高度最大的div元素的高度
這是一個簡單的插件,利用.height()傳回頁面中高度最大的div元素的高度。
維護Chainability
很多時候,一個插件的意圖僅僅是以某種方式修改收集的元素,并把它們傳遞給鍊中的下一個方法。 這是jQuery的設計之美,是jQuery如此受歡迎的原因之一。 是以,要保持一個插件的chainability,你必須確定你的插件傳回this關鍵字。
(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關鍵字,它保持了chainability,這樣jQuery收集的元素可以繼續被jQuery方法如.css控制。 是以,如果你的插件不傳回固有的價值,你應該總是在其作用範圍内傳回this關鍵字。 此外,你可能會推斷出,傳遞給插件的參數将會在插件的作用範圍内被傳遞。 是以,在前面的例子,字元串’width’變成了插件的類型參數。
預設值和選項
對于比較複雜的和提供了許多選項可定制的的插件,最好有一個當插件被調用的時候可以被拓展的預設設定(通過使用$.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'
在這個例子中,調用tooltip插件時覆寫了預設設定中的location選項,background-color選項保持預設值,是以最終被調用的設定值為:
{
'location': 'left',
'background-color': 'blue'
這是一個很靈活的方式,提供一個高度可配置的插件,而無需開發人員定義所有可用的選項。
命名空間
正确命名空間你的插件是插件開發的一個非常重要的一部分。 正确的命名空間,可以保證你的插件将有一個非常低的機會被其他插件或同一頁上的其他代碼覆寫。 命名空間也使得你的生活作為一個插件開發人員更容易,因為它可以幫助你更好地跟蹤你的方法,事件和資料。
插件方法
在任何情況下,一個單獨的插件不應該在jQuery.fnjQuery.fn對象裡有多個命名空間。
(function ($) {
$.fn.tooltip = function (options) {
// this
};
$.fn.tooltipShow = function () {
// is
};
$.fn.tooltipHide = function () {
// bad
};
$.fn.tooltipUpdate = function (content) {
// !!!
這是不被鼓勵的,因為它$.fn使$.fn命名空間混亂。 為了解決這個問題,你應該收集對象文本中的所有插件的方法,通過傳遞該方法的字元串名稱給插件以調用它們。
(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!');
這種類型的插件架構允許您封裝所有的方法在父包中,通過傳遞該方法的字元串名稱和額外的此方法需要的參數來調用它們。 這種方法的封裝和架構類型是jQuery插件社群的标準,它被無數的插件在使用,包括jQueryUI中的插件和widgets。
事件
<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();
//一段時間之後... ...
$('#fun').tooltip('destroy');
在這個例子中,當tooltip通過init方法初始化時,它将reposition方法綁定到resize事件并給reposition非那方法賦予命名空間通過追加.tooltip。 稍後, 當開發人員需要銷毀tooltip的時候,我們可以同時解除其中reposition方法和resize事件的綁定,通過傳遞reposition的命名空間給插件。 這使我們能夠安全地解除事件的綁定并不會影響到此插件之外的綁定。
資料
通常在插件開發的時候,你可能需要記錄或者檢查你的插件是否已經被初始化給了一個元素。 使用jQuery的data方法是一個很好的基于元素的記錄變量的途徑。盡管如此,相對于記錄大量的不同名字的分離的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);
總結和最佳做法
- 始終包裹在一個封閉的插件:
(function($) {
/* plugin goes here */
- 不要備援包裹this關鍵字在插件的功能範圍内
- 除非插件傳回特定值,否則總是傳回this關鍵字來維持chainability 。
- 傳遞一個可拓展的預設對象參數而不是大量的參數給插件。
- 不要在一個插件中多次命名不同方法。
- 始終命名空間的方法,事件和資料