擴(kuò)展jQuery插件和方法的作用是非常強(qiáng)大的,它可以節(jié)省大量開發(fā)時(shí)間。這篇文章將概述jQuery插件開發(fā)的基本知識(shí),最佳做法和常見的陷阱。
入門
編寫一個(gè)jQuery插件開始于給jQuery.fn加入??新的功能屬性,此處添加的對象屬性的名稱就是你插件的名稱:
jQuery.fn.myPlugin = function(){ //你自己的插件代碼 };
用戶非常喜歡的$符號哪里去了? 它仍然存在,但是,為了避免和其他JavaScript庫沖突,我們最好將jQuery傳遞給一個(gè)自我執(zhí)行的封閉程序,jQuery在此程序中映射為$符號,這樣可以避免$號被其他庫覆寫。
(function ($) { $.fn.m??yPlugin = function () { //你自己的插件代碼 }; })(jQuery);
在這個(gè)封閉程序中,我們可以無限制的使用$符號來表示jQuery函數(shù)。
環(huán)境
現(xiàn)在,我們可以開始編寫實(shí)際的插件代碼。 但是,在這之前,我們必須得對插件所處的環(huán)境有個(gè)概念。?在插件的范圍里, this關(guān)鍵字代表了這個(gè)插件將要執(zhí)行的jQuery對象,?這里容易產(chǎn)生一個(gè)普遍的誤區(qū),因?yàn)樵谄渌琧allback的jQuery函數(shù)中,this關(guān)鍵字代表了原生的DOM元素。這常常會(huì)導(dǎo)致開發(fā)者誤將this關(guān)鍵字無謂的包在jQuery中,如下所示。
(function ($) { $.fn.m??yPlugin = function () { //此處沒有必要將this包在$號中如$(this),因?yàn)閠his已經(jīng)是一個(gè)jQuery對象。 //$(this)等同于 $($('#element')); this.fadeIn('normal', function () { //此處callback函數(shù)中this關(guān)鍵字代表一個(gè)DOM元素 }); }; })(jQuery); $('#element').myPlugin();
基礎(chǔ)知識(shí)
現(xiàn)在,我們理解了jQuery插件的基礎(chǔ)知識(shí),讓我們寫一個(gè)插件,做一些事情。
(function ($) { $.fn.m??axHeight = function () { var max = 0; this.each(function () { max = Math.max(max, $(this).height()); }); return max; }; })(jQuery); var tallest = $('div').maxHeight(); //返回高度最大的div元素的高度
這是一個(gè)簡單的插件,利用.height()返回頁面中高度最大的div元素的高度。
維護(hù)Chainability
很多時(shí)候,一個(gè)插件的意圖僅僅是以某種方式修改收集的元素,并把它們傳遞給鏈中的下一個(gè)方法。 這是jQuery的設(shè)計(jì)之美,是jQuery如此受歡迎的原因之一。 因此,要保持一個(gè)插件的chainability,你必須確保你的插件返回this關(guān)鍵字。
(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關(guān)鍵字,它保持了chainability,這樣jQuery收集的元素可以繼續(xù)被jQuery方法如.css控制。 因此,如果你的插件不返回固有的價(jià)值,你應(yīng)該總是在其作用范圍內(nèi)返回this關(guān)鍵字。 此外,你可能會(huì)推斷出,傳遞給插件的參數(shù)將會(huì)在插件的作用范圍內(nèi)被傳遞。 因此,在前面的例子,字符串’width’變成了插件的類型參數(shù)。
默認(rèn)值和選項(xiàng)
對于比較復(fù)雜的和提供了許多選項(xiàng)可定制的的插件,最好有一個(gè)當(dāng)插件被調(diào)用的時(shí)候可以被拓展的默認(rèn)設(shè)置(通過使用$.extend)。 因此,相對于調(diào)用一個(gè)有大量參數(shù)的插件,你可以調(diào)用一個(gè)對象參數(shù),包含你了你想覆寫的設(shè)置。
(function ($) { $.fn.tooltip = function (options) { //創(chuàng)建一些默認(rèn)值,拓展任何被提供的選項(xiàng) var settings = $.extend({ 'location': 'top', 'background-color': 'blue' }, options); return this.each(function () { // Tooltip插件代碼 }); }; })(jQuery); $('div').tooltip({ 'location': 'left' });
在這個(gè)例子中,調(diào)用tooltip插件時(shí)覆寫了默認(rèn)設(shè)置中的location選項(xiàng),background-color選項(xiàng)保持默認(rèn)值,所以最終被調(diào)用的設(shè)定值為:
{ 'location': 'left', 'background-color': 'blue' }
這是一個(gè)很靈活的方式,提供一個(gè)高度可配置的插件,而無需開發(fā)人員定義所有可用的選項(xiàng)。
命名空間
正確命名空間你的插件是插件開發(fā)的一個(gè)非常重要的一部分。 正確的命名空間,可以保證你的插件將有一個(gè)非常低的機(jī)會(huì)被其他插件或同一頁上的其他代碼覆蓋。 命名空間也使得你的生活作為一個(gè)插件開發(fā)人員更容易,因?yàn)樗梢詭椭愀玫馗櫮愕姆椒ǎ录蛿?shù)據(jù)。
插件方法
在任何情況下,一個(gè)單獨(dú)的插件不應(yīng)該在jQuery.fn
jQuery.fn對象里有多個(gè)命名空間。
(function ($) { $.fn.tooltip = function (options) { // this }; $.fn.tooltipShow = function () { // is }; $.fn.tooltipHide = function () { // bad }; $.fn.tooltipUpdate = function (content) { // !!! }; })(jQuery);
這是不被鼓勵(lì)的,因?yàn)樗?code>$.fn使$.fn命名空間混亂。 為了解決這個(gè)問題,你應(yīng)該收集對象文本中的所有插件的方法,通過傳遞該方法的字符串名稱給插件以調(diào)用它們。
(function ($) { var methods = { init: function (options) { // this }, show: function () { // is }, hide: function () { // good }, update: function (content) { // !!! } }; $.fn.tooltip = function (method) { // 方法調(diào)用 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); //調(diào)用init方法 $('div').tooltip(); //調(diào)用init方法 $('div').tooltip({ foo: 'bar' }); // 調(diào)用hide方法 $('div').tooltip('hide'); //調(diào)用Update方法 $('div').tooltip('update', 'This is the new tooltip content!');
這種類型的插件架構(gòu)允許您封裝所有的方法在父包中,通過傳遞該方法的字符串名稱和額外的此方法需要的參數(shù)來調(diào)用它們。 這種方法的封裝和架構(gòu)類型是jQuery插件社區(qū)的標(biāo)準(zhǔn),它被無數(shù)的插件在使用,包括jQueryUI中的插件和widgets。
事件
一個(gè)鮮為人知bind方法的功能即允許綁定事件命名空間。 如果你的插件綁定一個(gè)事件,一個(gè)很好的做法是賦予此事件命名空間。 通過這種方式,當(dāng)你在解除綁定的時(shí)候不會(huì)干擾其他可能已經(jīng)綁定的同一類型事件。?? 你可以通過追加命名空間到你需要綁定的的事件通過 ‘.<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(); //一段時(shí)間之后... ... $('#fun').tooltip('destroy');
在這個(gè)例子中,當(dāng)tooltip通過init方法初始化時(shí),它將reposition方法綁定到resize事件并給reposition非那方法賦予命名空間通過追加.tooltip。?稍后, 當(dāng)開發(fā)人員需要銷毀tooltip的時(shí)候,我們可以同時(shí)解除其中reposition方法和resize事件的綁定,通過傳遞reposition的命名空間給插件。 這使我們能夠安全地解除事件的綁定并不會(huì)影響到此插件之外的綁定。
數(shù)據(jù)
通常在插件開發(fā)的時(shí)候,你可能需要記錄或者檢查你的插件是否已經(jīng)被初始化給了一個(gè)元素。 使用jQuery的data方法是一個(gè)很好的基于元素的記錄變量的途徑。盡管如此,相對于記錄大量的不同名字的分離的data,??使用一個(gè)單獨(dú)的對象保存所有變量,并通過一個(gè)單獨(dú)的命名空間讀取這個(gè)對象不失為一個(gè)更好的方法。
(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);
將數(shù)據(jù)通過命名空間封裝在一個(gè)對象中,可以更容易的從一個(gè)集中的位置讀取所有插件的屬性。
總結(jié)和最佳做法
編寫jQuery插件允許你做出庫,將最有用的功能集成到可重用的代碼,可以節(jié)省開發(fā)者的時(shí)間,使開發(fā)更高效。 開發(fā)jQuery插件時(shí),要牢記:
- 始終包裹在一個(gè)封閉的插件:
(function($) { /* plugin goes here */ })(jQuery);
- 不要冗余包裹this關(guān)鍵字在插件的功能范圍內(nèi)
- 除非插件返回特定值,否則總是返回this關(guān)鍵字來維持chainability 。
- 傳遞一個(gè)可拓展的默認(rèn)對象參數(shù)而不是大量的參數(shù)給插件。
- 不要在一個(gè)插件中多次命名不同方法。
- 始終命名空間的方法,事件和數(shù)據(jù)。