jQuery 插件的開發包括兩種:
一種是類級別的插件開發,即給jQuery 添加新的全局函數,相當于給jQuery 類本身添加方法。jQuery 的全局函數就是屬于jQuery 命名空間的函數,另一種是對象級別的插件開發,即給jQuery 對象添加方法。下面就兩種函數的開發做詳細的說明。
1 、類級別的插件開發
類級別的插件開發最直接的理解就是給jQuery 類添加類方法,可以理解為添加靜態方法。典型的例子就是$.AJAX() 這個函數,將函數定義于jQuery 的命名空間中。關于類級別的插件開發可以采用如下幾種形式進行擴展:
1.1 添加一個新的全局函數
添加一個全局函數,我們只需如下定義:
Java代碼 ?
jQuery.foo?=?function()?{??? alert('This?is?a?test.?This?is?only?a?test.');?? };???? jQuery.foo = function() { alert('This is a test. This is only a test.');};
?
?
1.2 增加多個全局函數
添加多個全局函數,可采用如下定義:
Java代碼 ?
jQuery.foo?=?function()?{??? alert('This?is?a?test.?This?is?only?a?test.');?? };?? jQuery.bar?=?function(param)?{??? alert('This?function?takes?a?parameter,?which?is?"'?+?param?+?'".');?? };??? 調用時和一個函數的一樣的:jQuery.foo();jQuery.bar();或者$.foo();$.bar('bar');?? jQuery.foo = function() { alert('This is a test. This is only a test.');};jQuery.bar = function(param) { alert('This function takes a parameter, which is "' + param + '".');}; 調用時和一個函數的一樣的:jQuery.foo();jQuery.bar();或者$.foo();$.bar('bar');
1.3 使用jQuery.extend(object);
Java代碼 ?
jQuery.extend({?????? foo:?function()?{?????? alert('This?is?a?test.?This?is?only?a?test.');?????? },?????? bar:?function(param)?{?????? alert('This?function?takes?a?parameter,?which?is?"'?+?param?+'".');?????? }????? });?? jQuery.extend({ foo: function() { alert('This is a test. This is only a test.'); }, bar: function(param) { alert('This function takes a parameter, which is "' + param +'".'); } });
?
1.4 使用命名空間
雖然在jQuery 命名空間中,我們禁止使用了大量的javaScript 函數名和變量名。但是仍然不可避免某些函數或變量名將于其他jQuery 插件沖突,因此我們習慣將一些方法封裝到另一個自定義的命名空間。
Java代碼 ?
jQuery.myPlugin?=?{?????????? foo:function()?{?????????? alert('This?is?a?test.?This?is?only?a?test.');?????????? },?????????? bar:function(param)?{?????????? alert('This?function?takes?a?parameter,?which?is?"'?+?param?+?'".');???? }????????? };?? 采用命名空間的函數仍然是全局函數,調用時采用的方法:?? $.myPlugin.foo();????????? $.myPlugin.bar('baz');?? jQuery.myPlugin = { foo:function() { alert('This is a test. This is only a test.'); }, bar:function(param) { alert('This function takes a parameter, which is "' + param + '".'); } };采用命名空間的函數仍然是全局函數,調用時采用的方法:$.myPlugin.foo(); $.myPlugin.bar('baz');
?
通過這個技巧(使用獨立的插件名),我們可以避免命名空間內函數的沖突。
2 、對象級別的插件開發
對象級別的插件開發需要如下的兩種形式:、
形式1 :??
Java代碼 ?
(function($){????? $.fn.extend({????? pluginName:function(opt,callback){????? ??????????//?Our?plugin?implementation?code?goes?here.??????? }????? })????? })(jQuery);????? (function($){ $.fn.extend({ pluginName:function(opt,callback){ // Our plugin implementation code goes here. } }) })(jQuery);
形式2 :
Java代碼 ?
(function($)?{??????? $.fn.pluginName?=?function()?{????? ?????//?Our?plugin?implementation?code?goes?here.????? };????? })(jQuery);?????? (function($) { $.fn.pluginName = function() { // Our plugin implementation code goes here. }; })(jQuery); ?????? 上面定義了一個
jQuery 函數
, 形參是
$ ,函數定義完成之后
, 把
jQuery 這個實參傳遞進去
. 立即調用執行。這樣的好處是
, 我們在寫
jQuery 插件時
, 也可以使用
$ 這個別名
, 而不會與
prototype 引起沖突
.
2.1 在JQuery 名稱空間下申明一個名字
這是一個單一插件的腳本。如果你的腳本中包含多個插件,或者互逆的插件(例如: $.fn.doSomething() 和 $.fn.undoSomething() ),那么你需要聲明多個函數名字。但是,通常當我們編寫一個插件時,力求僅使用一個名字來包含它的所有內容。我們的示例插件命名為“highlight “????
?
Java代碼 ?
$.fn.hilight?=?function()?{???? ??//?Our?plugin?implementation?code?goes?here.???? };???? 我們的插件通過這樣被調用:?? $('#myDiv').hilight();?????
$.fn.hilight = function() { // Our plugin implementation code goes here. }; 我們的插件通過這樣被調用:$('#myDiv').hilight();
?
但是如果我們需要分解我們的實現代碼為多個函數該怎么辦?有很多原因:設計上的需要;這樣做更容易或更易讀的實現;而且這樣更符合面向對象。這真是一個麻煩事,把功能實現分解成多個函數而不增加多余的命名空間。出于認識到和利用函數是javascript 中最基本的類對象,我們可以這樣做。就像其他對象一樣,函數可以被指定為屬性。因此我們已經聲明“hilight” 為jQuery 的屬性對象,任何其他的屬性或者函數我們需要暴露出來的,都可以在"hilight" 函數中被聲明屬性。稍后繼續。 2.2 接受options 參數以控制插件的行為
讓我們為我們的插件添加功能指定前景色和背景色的功能。我們也許會讓選項像一個options 對象傳遞給插件函數。例如:???
Java代碼 ?
//?plugin?definition???? $.fn.hilight?=?function(options)?{???? ??var?defaults?=?{???? ????foreground:?'red',???? ????background:?'yellow'???? ??};???? ??//?Extend?our?default?options?with?those?provided.???? ??var?opts?=?$.extend(defaults,?options);???? ??//?Our?plugin?implementation?code?goes?here.???? };???? 我們的插件可以這樣被調用:?? $('#myDiv').hilight({???? ??foreground:?'blue'???? });?????
// plugin definition $.fn.hilight = function(options) { var defaults = { foreground: 'red', background: 'yellow' }; // Extend our default options with those provided. var opts = $.extend(defaults, options); // Our plugin implementation code goes here. }; 我們的插件可以這樣被調用:$('#myDiv').hilight({ foreground: 'blue' });
?
2.3 暴露插件的默認設置
我們應該對上面代碼的一種改進是暴露插件的默認設置。這對于讓插件的使用者更容易用較少的代碼覆蓋和修改插件。接下來我們開始利用函數對象。?????
?
Java代碼 ?
//?plugin?definition???? $.fn.hilight?=?function(options)?{???? ??//?Extend?our?default?options?with?those?provided.???? ??//?Note?that?the?first?arg?to?extend?is?an?empty?object?-???? ??//?this?is?to?keep?from?overriding?our?"defaults"?object.???? ??var?opts?=?$.extend({},?$.fn.hilight.defaults,?options);???? ??//?Our?plugin?implementation?code?goes?here.???? };???? //?plugin?defaults?-?added?as?a?property?on?our?plugin?function???? $.fn.hilight.defaults?=?{???? ??foreground:?'red',???? ??background:?'yellow'???? };????? 現在使用者可以包含像這樣的一行在他們的腳本里:?? //這個只需要調用一次,且不一定要在ready塊中調用?? $.fn.hilight.defaults.foreground?=?'blue';???? 接下來我們可以像這樣使用插件的方法,結果它設置藍色的前景色:?? $('#myDiv').hilight();???
// plugin definition $.fn.hilight = function(options) { // Extend our default options with those provided. // Note that the first arg to extend is an empty object - // this is to keep from overriding our "defaults" object. var opts = $.extend({}, $.fn.hilight.defaults, options); // Our plugin implementation code goes here. }; // plugin defaults - added as a property on our plugin function $.fn.hilight.defaults = { foreground: 'red', background: 'yellow' }; 現在使用者可以包含像這樣的一行在他們的腳本里://這個只需要調用一次,且不一定要在ready塊中調用$.fn.hilight.defaults.foreground = 'blue'; 接下來我們可以像這樣使用插件的方法,結果它設置藍色的前景色:$('#myDiv').hilight();
?
如你所見,我們允許使用者寫一行代碼在插件的默認前景色。而且使用者仍然在需要的時候可以有選擇的覆蓋這些新的默認值:
// 覆蓋插件缺省的背景顏色?
$.fn.hilight.defaults.foreground = 'blue';?
// ...?
// 使用一個新的缺省設置調用插件?
$('.hilightDiv').hilight();?
// ...?
// 通過傳遞配置參數給插件方法來覆蓋缺省設置?
$('#green').hilight({?
? foreground: 'green'?
});??
2.4 適當的暴露一些函數
這段將會一步一步對前面那段代碼通過有意思的方法擴展你的插件(同時讓其他人擴展你的插件)。例如,我們插件的實現里面可以定義一個名叫"format" 的函數來格式化高亮文本。我們的插件現在看起來像這樣,默認的format 方法的實現部分在hiligth 函數下面。
Java代碼 ?
//?plugin?definition???? $.fn.hilight?=?function(options)?{???? ??//?iterate?and?reformat?each?matched?element???? ??return?this.each(function()?{???? ????var?$this?=?$(this);???? ????//?...???? ????var?markup?=?$this.html();???? ????//?call?our?format?function???? ????markup?=?$.fn.hilight.format(markup);???? ????$this.html(markup);???? ??});???? };???? //?define?our?format?function???? $.fn.hilight.format?=?function(txt)?{???? return?'<strong>'?+?txt?+?'</strong>';???? };????? // plugin definition $.fn.hilight = function(options) { // iterate and reformat each matched element return this.each(function() { var $this = $(this); // ... var markup = $this.html(); // call our format function markup = $.fn.hilight.format(markup); $this.html(markup); }); }; // define our format function $.fn.hilight.format = function(txt) { return '<strong>' + txt + '</strong>'; }; ????? 我們很容易的支持
options 對象中的其他的屬性通過允許一個回調函數來覆蓋默認的設置。這是另外一個出色的方法來修改你的插件。這里展示的技巧是進一步有效的暴露
format 函數進而讓他能被重新定義。通過這技巧,是其他人能夠傳遞他們自己設置來覆蓋你的插件,換句話說,這樣其他人也能夠為你的插件寫插件。
????? 考慮到這個篇文章中我們建立的無用的插件,你也許想知道究竟什么時候這些會有用。一個真實的例子是
Cycle 插件
. 這個
Cycle 插件是一個滑動顯示插件,他能支持許多內部變換作用到滾動,滑動,漸變消失等。但是實際上,沒有辦法定義也許會應用到滑動變化上每種類型的效果。那是這種擴展性有用的地方。
Cycle 插件對使用者暴露
"transitions" 對象,使他們添加自己變換定義。插件中定義就像這樣:
$.fn.cycle.transitions = {?
// ...?
};?
這個技巧使其他人能定義和傳遞變換設置到Cycle 插件。
2.5 保持私有函數的私有性
這種技巧暴露你插件一部分來被覆蓋是非常強大的。但是你需要仔細思考你實現中暴露的部分。一但被暴露,你需要在頭腦中保持任何對于參數或者語義的改動也許會破壞向后的兼容性。一個通理是,如果你不能肯定是否暴露特定的函數,那么你也許不需要那樣做。
那么我們怎么定義更多的函數而不攪亂命名空間也不暴露實現呢?這就是閉包的功能。為了演示,我們將會添加另外一個“debug” 函數到我們的插件中。這個 debug 函數將為輸出被選中的元素格式到firebug 控制臺。為了創建一個閉包,我們將包裝整個插件定義在一個函數中。?
Java代碼 ?
?(function($)?{???? ??//?plugin?definition???? ??$.fn.hilight?=?function(options)?{???? ????debug(this);???? ????//?...???? ??};???? ??//?private?function?for?debugging???? ??function?debug($obj)?{???? ????if?(window.console?&&?window.console.log)???? ??????window.console.log('hilight?selection?count:?'?+?$obj.size());???? ??};???? //??...???? })(jQuery);????
(function($) { // plugin definition $.fn.hilight = function(options) { debug(this); // ... }; // private function for debugging function debug($obj) { if (window.console && window.console.log) window.console.log('hilight selection count: ' + $obj.size()); }; // ... })(jQuery);
?
我們的“debug” 方法不能從外部閉包進入, 因此對于我們的實現是私有的。
2.6 支持Metadata 插件
在你正在寫的插件的基礎上,添加對Metadata 插件的支持能使他更強大。個人來說,我喜歡這個Metadata 插件,因為它讓你使用不多的"markup” 覆蓋插件的選項(這非常有用當創建例子時)。而且支持它非常簡單。更新:注釋中有一點優化建議。
Java代碼 ?
$.fn.hilight?=?function(options)?{???? ??//?...???? ??//?build?main?options?before?element?iteration???? ??var?opts?=?$.extend({},?$.fn.hilight.defaults,?options);???? ??return?this.each(function()?{???? ????var?$this?=?$(this);???? ????//?build?element?specific?options???? ????var?o?=?$.meta???$.extend({},?opts,?$this.data())?:?opts;???? ????//...??????
$.fn.hilight = function(options) { // ... // build main options before element iteration var opts = $.extend({}, $.fn.hilight.defaults, options); return this.each(function() { var $this = $(this); // build element specific options var o = $.meta ? $.extend({}, opts, $this.data()) : opts; //... ?
? 這些變動行做了一些事情:它是測試Metadata 插件是否被安裝如果它被安裝了,它能擴展我們的options 對象通過抽取元數據這行作為最后一個參數添加到JQuery.extend ,那么它將會覆蓋任何其它選項設置。現在我們能從"markup” 處驅動行為, 如果我們選擇了“markup” :
?調用的時候可以這樣寫: jQuery.foo();? 或?$.foo();?
?
Java代碼 ?
<!--??markup??-->???? <div?class="hilight?{?background:?'red',?foreground:?'white'?}">???? ??Have?a?nice?day!???? </div>???? <div?class="hilight?{?foreground:?'orange'?}">???? ??Have?a?nice?day!???? </div>???? <div?class="hilight?{?background:?'green'?}">???? ??Have?a?nice?day!???? </div>???? 現在我們能高亮哪些div僅使用一行腳本:?? $('.hilight').hilight();????? <!-- markup --> <div class="hilight { background: 'red', foreground: 'white' }"> Have a nice day! </div> <div class="hilight { foreground: 'orange' }"> Have a nice day! </div> <div class="hilight { background: 'green' }"> Have a nice day! </div> 現在我們能高亮哪些div僅使用一行腳本:$('.hilight').hilight();
?
2.7 整合 下面使我們的例子完成后的代碼:
????
Java代碼 ?
//?創建一個閉包???? (function($)?{???? ??//?插件的定義???? ??$.fn.hilight?=?function(options)?{???? ????debug(this);???? ????//?build?main?options?before?element?iteration???? ????var?opts?=?$.extend({},?$.fn.hilight.defaults,?options);???? ????//?iterate?and?reformat?each?matched?element???? ????return?this.each(function()?{???? ??????$this?=?$(this);???? ??????//?build?element?specific?options???? ??????var?o?=?$.meta???$.extend({},?opts,?$this.data())?:?opts;???? ??????//?update?element?styles???? ??????$this.css({???? ????????backgroundColor:?o.background,???? ????????color:?o.foreground???? ??????});???? ??????var?markup?=?$this.html();???? ??????//?call?our?format?function???? ??????markup?=?$.fn.hilight.format(markup);???? ??????$this.html(markup);???? ????});???? ??};???? ??//?私有函數:debugging???? ??function?debug($obj)?{???? ????if?(window.console?&&?window.console.log)???? ??????window.console.log('hilight?selection?count:?'?+?$obj.size());???? ??};???? ??//?定義暴露format函數???? ??$.fn.hilight.format?=?function(txt)?{???? ????return?'<strong>'?+?txt?+?'</strong>';???? ??};???? ??//?插件的defaults???? ??$.fn.hilight.defaults?=?{???? ????foreground:?'red',???? ????background:?'yellow'???? ??};???? //?閉包結束???? })(jQuery);?????
// 創建一個閉包 (function($) { // 插件的定義 $.fn.hilight = function(options) { debug(this); // build main options before element iteration var opts = $.extend({}, $.fn.hilight.defaults, options); // iterate and reformat each matched element return this.each(function() { $this = $(this); // build element specific options var o = $.meta ? $.extend({}, opts, $this.data()) : opts; // update element styles $this.css({ backgroundColor: o.background, color: o.foreground }); var markup = $this.html(); // call our format function markup = $.fn.hilight.format(markup); $this.html(markup); }); }; // 私有函數:debugging function debug($obj) { if (window.console && window.console.log) window.console.log('hilight selection count: ' + $obj.size()); }; // 定義暴露format函數 $.fn.hilight.format = function(txt) { return '<strong>' + txt + '</strong>'; }; // 插件的defaults $.fn.hilight.defaults = { foreground: 'red', background: 'yellow' }; // 閉包結束 })(jQuery);
?
這段設計已經讓我創建了強大符合規范的插件。我希望它能讓你也能做到。
3 、總結
jQuery 為開發插件提拱了兩個方法,分別是:
jQuery.fn.extend(object);? 給jQuery 對象添加方法。 jQuery.extend(object); ? 為擴展jQuery 類本身. 為類添加新的方法。
3.1 jQuery.fn.extend(object);
fn 是什么東西呢。查看jQuery 代碼,就不難發現。
jQuery.fn = jQuery.prototype = {??
init: function( selector, context ) {//.... ??
//......??
};???
原來 jQuery.fn = jQuery.prototype. 對prototype 肯定不會陌生啦。雖然 javascript 沒有明確的類的概念,但是用類來理解它,會更方便。jQuery 便是一個封裝得非常好的類,比如我們用語句 $("#btn1") 會生成一個 jQuery 類的實例。
jQuery.fn.extend(object); 對jQuery.prototype 進得擴展,就是為jQuery 類添加“ 成員函數” 。jQuery 類的實例可以使用這個“ 成員函數” 。
比如我們要開發一個插件,做一個特殊的編輯框,當它被點擊時,便alert 當前編輯框里的內容。可以這么做:
$.fn.extend({????????
???? alertWhileClick:function(){???????
???????? $(this).click(function(){??????
????????????? alert($(this).val());???????
????????? });???????
????? }???????
});???
$("#input1").alertWhileClick(); // 頁面上為:<input id="input1" type="text"/>
$("#input1") 為一個jQuery 實例,當它調用成員方法 alertWhileClick 后,便實現了擴展,每次被點擊時它會先彈出目前編輯里的內容。
3.2 jQuery.extend(object);
為jQuery 類添加添加類方法,可以理解為添加靜態方法。如:
$.extend({??
??? add:function(a,b){return a+b;}??
});??
便為 jQuery 添加一個為 add 的 “ 靜態方法” ,之后便可以在引入 jQuery 的地方,使用這個方法了,$.add(3,4); //return 7
總結
以上是生活随笔 為你收集整理的JQuery闭包,插件的写法 的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔 網站內容還不錯,歡迎將生活随笔 推薦給好友。