jQuery 插件的開發(fā)包括兩種:
一種是類級別的插件開發(fā),即給jQuery 添加新的全局函數(shù),相當(dāng)于給jQuery 類本身添加方法。jQuery 的全局函數(shù)就是屬于jQuery 命名空間的函數(shù),另一種是對象級別的插件開發(fā),即給jQuery 對象添加方法。下面就兩種函數(shù)的開發(fā)做詳細的說明。
1 、類級別的插件開發(fā)
類級別的插件開發(fā)最直接的理解就是給jQuery 類添加類方法,可以理解為添加靜態(tài)方法。典型的例子就是$.AJAX() 這個函數(shù),將函數(shù)定義于jQuery 的命名空間中。關(guān)于類級別的插件開發(fā)可以采用如下幾種形式進行擴展:
1.1 添加一個新的全局函數(shù)
添加一個全局函數(shù),我們只需如下定義:
?
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 增加多個全局函數(shù)
添加多個全局函數(shù),可采用如下定義:
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?+?'".'); ?? };? ?? 調(diào)用時和一個函數(shù)的一樣的: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 + '".');
};
調(diào)用時和一個函數(shù)的一樣的: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 函數(shù)名和變量名。但是仍然不可避免某些函數(shù)或變量名將于其他jQuery 插件沖突,因此我們習(xí)慣將一些方法封裝到另一個自定義的命名空間。
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?+?'".');?? ?? }??????? ?? }; ?? 采用命名空間的函數(shù)仍然是全局函數(shù),調(diào)用時采用的方法: ?? $.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 + '".');
}
};
采用命名空間的函數(shù)仍然是全局函數(shù),調(diào)用時采用的方法:
$.myPlugin.foo();
$.myPlugin.bar('baz');
?
通過這個技巧(使用獨立的插件名),我們可以避免命名空間內(nèi)函數(shù)的沖突。
2 、對象級別的插件開發(fā)
對象級別的插件開發(fā)需要如下的兩種形式:、
形式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 函數(shù)
, 形參是
$ ,函數(shù)定義完成之后
, 把
jQuery 這個實參傳遞進去
. 立即調(diào)用執(zhí)行。這樣的好處是
, 我們在寫
jQuery 插件時
, 也可以使用
$ 這個別名
, 而不會與
prototype 引起沖突
. 2.1 在 JQuery 名稱空間下申明一個名字
這是一個單一插件的腳本。如果你的腳本中包含多個插件,或者互逆的插件(例如: $.fn.doSomething() 和 $.fn.undoSomething() ),那么你需要聲明多個函數(shù)名字。但是,通常當(dāng)我們編寫一個插件時,力求僅使用一個名字來包含它的所有內(nèi)容。我們的示例插件命名為“highlight “????
?
Java代碼
$.fn.hilight?=?function()?{?? ?? ??//?Our?plugin?implementation?code?goes?here.?? ?? };?? ?? 我們的插件通過這樣被調(diào)用: ?? $('#myDiv').hilight();????? $.fn.hilight = function() { // Our plugin implementation code goes here.
};
我們的插件通過這樣被調(diào)用:
$('#myDiv').hilight();
?
但是如果我們需要分解我們的實現(xiàn)代碼為多個函數(shù)該怎么辦?有很多原因:設(shè)計上的需要;這樣做更容易或更易讀的實現(xiàn);而且這樣更符合面向?qū)ο蟆?這真是一個麻煩事,把功能實現(xiàn)分解成多個函數(shù)而不增加多余的命名空間。出于認識到和利用函數(shù)是javascript 中最基本的類對象,我們可以這樣做。就像其他對象一樣,函數(shù)可以被指定為屬性。因此我們已經(jīng)聲明“hilight” 為jQuery 的屬性對象,任何其他的屬性或者函數(shù)我們需要暴露出來的,都可以在"hilight" 函數(shù)中被聲明屬性。稍后繼續(xù)。2.2 接受 options 參數(shù)以控制插件的行為
讓我們?yōu)槲覀兊牟寮砑庸δ苤付ㄇ熬吧捅尘吧墓δ堋N覀円苍S會讓選項像一個options 對象傳遞給插件函數(shù)。例如:???
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.?? ?? };?? ?? 我們的插件可以這樣被調(diào)用: ?? $('#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.
};
我們的插件可以這樣被調(diào)用:
$('#myDiv').hilight({ foreground: 'blue'
});
?
2.3 暴露插件的默認設(shè)置
我們應(yīng)該對上面代碼的一種改進是暴露插件的默認設(shè)置。這對于讓插件的使用者更容易用較少的代碼覆蓋和修改插件。接下來我們開始利用函數(shù)對象。?????
?
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'?? ?? };??? ?? 現(xiàn)在使用者可以包含像這樣的一行在他們的腳本里: ?? //這個只需要調(diào)用一次,且不一定要在ready塊中調(diào)用 ?? $.fn.hilight.defaults.foreground?=?'blue';?? ?? 接下來我們可以像這樣使用插件的方法,結(jié)果它設(shè)置藍色的前景色: ?? $('#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'
};
現(xiàn)在使用者可以包含像這樣的一行在他們的腳本里:
//這個只需要調(diào)用一次,且不一定要在ready塊中調(diào)用
$.fn.hilight.defaults.foreground = 'blue';
接下來我們可以像這樣使用插件的方法,結(jié)果它設(shè)置藍色的前景色:
$('#myDiv').hilight();
?
如你所見,我們允許使用者寫一行代碼在插件的默認前景色。而且使用者仍然在需要的時候可以有選擇的覆蓋這些新的默認值:
// 覆蓋插件缺省的背景顏色?
$.fn.hilight.defaults.foreground = 'blue';?
// ...?
// 使用一個新的缺省設(shè)置調(diào)用插件?
$('.hilightDiv').hilight();?
// ...?
// 通過傳遞配置參數(shù)給插件方法來覆蓋缺省設(shè)置?
$('#green').hilight({?
?foreground: 'green'?
});??
2.4 適當(dāng)?shù)谋┞兑恍┖瘮?shù)
這段將會一步一步對前面那段代碼通過有意思的方法擴展你的插件(同時讓其他人擴展你的插件)。例如,我們插件的實現(xiàn)里面可以定義一個名叫"format" 的函數(shù)來格式化高亮文本。我們的插件現(xiàn)在看起來像這樣,默認的format 方法的實現(xiàn)部分在hiligth 函數(shù)下面。
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 對象中的其他的屬性通過允許一個回調(diào)函數(shù)來覆蓋默認的設(shè)置。這是另外一個出色的方法來修改你的插件。這里展示的技巧是進一步有效的暴露
format 函數(shù)進而讓他能被重新定義。通過這技巧,是其他人能夠傳遞他們自己設(shè)置來覆蓋你的插件,換句話說,這樣其他人也能夠為你的插件寫插件。
????? 考慮到這個篇文章中我們建立的無用的插件,你也許想知道究竟什么時候這些會有用。一個真實的例子是
Cycle 插件
. 這個
Cycle 插件是一個滑動顯示插件,他能支持許多內(nèi)部變換作用到滾動,滑動,漸變消失等。但是實際上,沒有辦法定義也許會應(yīng)用到滑動變化上每種類型的效果。那是這種擴展性有用的地方。
Cycle 插件對使用者暴露
"transitions" 對象,使他們添加自己變換定義。插件中定義就像這樣:
$.fn.cycle.transitions = {?
// ...?
};?
這個技巧使其他人能定義和傳遞變換設(shè)置到Cycle 插件。
2.5 保持私有函數(shù)的私有性
這種技巧暴露你插件一部分來被覆蓋是非常強大的。但是你需要仔細思考你實現(xiàn)中暴露的部分。一但被暴露,你需要在頭腦中保持任何對于參數(shù)或者語義的改動也許會破壞向后的兼容性。一個通理是,如果你不能肯定是否暴露特定的函數(shù),那么你也許不需要那樣做。
那么我們怎么定義更多的函數(shù)而不攪亂命名空間也不暴露實現(xiàn)呢?這就是閉包的功能。為了演示,我們將會添加另外一個“debug” 函數(shù)到我們的插件中。這個 debug 函數(shù)將為輸出被選中的元素格式到firebug 控制臺。為了創(chuàng)建一個閉包,我們將包裝整個插件定義在一個函數(shù)中。?
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” 方法不能從外部閉包進入, 因此對于我們的實現(xiàn)是私有的。
2.6 支持 Metadata 插件
在你正在寫的插件的基礎(chǔ)上,添加對Metadata 插件的支持能使他更強大。個人來說,我喜歡這個Metadata 插件,因為它讓你使用不多的"markup” 覆蓋插件的選項(這非常有用當(dāng)創(chuàng)建例子時)。而且支持它非常簡單。更新:注釋中有一點優(yōu)化建議。
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 對象通過抽取元數(shù)據(jù)這行作為最后一個參數(shù)添加到JQuery.extend ,那么它將會覆蓋任何其它選項設(shè)置。現(xiàn)在我們能從"markup” 處驅(qū)動行為, 如果我們選擇了“markup” :
?調(diào)用的時候可以這樣寫: 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>?? ?? 現(xiàn)在我們能高亮哪些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>
現(xiàn)在我們能高亮哪些div僅使用一行腳本:
$('.hilight').hilight();
?
2.7 整合 下面使我們的例子完成后的代碼:
????
Java代碼
//?創(chuàng)建一個閉包?? ?? (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);?? ?? ????});?? ?? ??};?? ?? ??//?私有函數(shù):debugging?? ?? ??function?debug($obj)?{?? ?? ????if?(window.console?&&?window.console.log)?? ?? ??????window.console.log('hilight?selection?count:?'?+?$obj.size());?? ?? ??};?? ?? ??//?定義暴露format函數(shù)?? ?? ??$.fn.hilight.format?=?function(txt)?{?? ?? ????return?'<strong>'?+?txt?+?'</strong>';?? ?? ??};?? ?? ??//?插件的defaults?? ?? ??$.fn.hilight.defaults?=?{?? ?? ????foreground:?'red',?? ?? ????background:?'yellow'?? ?? ??};?? ?? //?閉包結(jié)束?? ?? })(jQuery);????? // 創(chuàng)建一個閉包
(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); }); }; // 私有函數(shù):debugging function debug($obj) { if (window.console && window.console.log) window.console.log('hilight selection count: ' + $obj.size()); }; // 定義暴露format函數(shù) $.fn.hilight.format = function(txt) { return '<strong>' + txt + '</strong>'; }; // 插件的defaults $.fn.hilight.defaults = { foreground: 'red', background: 'yellow' };
// 閉包結(jié)束
})(jQuery);
?
這段設(shè)計已經(jīng)讓我創(chuàng)建了強大符合規(guī)范的插件。我希望它能讓你也能做到。
3 、總結(jié)
jQuery 為開發(fā)插件提拱了兩個方法,分別是:
jQuery.fn.extend(object);? 給jQuery 對象添加方法。 jQuery.extend(object); ? 為擴展jQuery 類本身. 為類添加新的方法。
3.1 jQuery.fn.extend(object);
fn 是什么東西呢。查看jQuery 代碼,就不難發(fā)現(xiàn)。
jQuery.fn = jQuery.prototype = {??
init: function( selector, context ) {//.... ??
//......??
};???
原來 jQuery.fn = jQuery.prototype. 對prototype 肯定不會陌生啦。雖然 javascript 沒有明確的類的概念,但是用類來理解它,會更方便。jQuery 便是一個封裝得非常好的類,比如我們用 語句 $("#btn1") 會生成一個 jQuery 類的實例。
jQuery.fn.extend(object); 對jQuery.prototype 進得擴展,就是為jQuery 類添加“ 成員函數(shù)” 。jQuery 類的實例可以使用這個“ 成員函數(shù)” 。
比如我們要開發(fā)一個插件,做一個特殊的編輯框,當(dāng)它被點擊時,便alert 當(dāng)前編輯框里的內(nèi)容。可以這么做:
$.fn.extend({????????
???? alertWhileClick:function(){???????
???????? $(this).click(function(){??????
????????????? alert($(this).val());???????
????????? });???????
????? }???????
});???
$("#input1").alertWhileClick(); // 頁面上為:<input id="input1" type="text"/>
$("#input1") 為一個jQuery 實例,當(dāng)它調(diào)用成員方法 alertWhileClick 后,便實現(xiàn)了擴展,每次被點擊時它會先彈出目前編輯里的內(nèi)容。
3.2 jQuery.extend(object);
為jQuery 類添加添加類方法,可以理解為添加靜態(tài)方法。如:
$.extend({??
??? add:function(a,b){return a+b;}??
});??
便為 jQuery 添加一個為 add 的 “ 靜態(tài)方法” ,之后便可以在引入 jQuery 的地方,使用這個方法了,$.add(3,4); //return 7
?
?
轉(zhuǎn)載于:https://www.cnblogs.com/silverLee/archive/2009/12/22/1629925.html
總結(jié)
以上是生活随笔 為你收集整理的jQuery插件开发全解析 的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔 網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔 推薦給好友。