若不清楚什麼是 jQuery 外掛、或不知道如何撰寫,建議先參考官方網站的 jQuery Authoring Guidelines。以下整理幾點我認為好的外掛應具備的要求:
1. 在 jQuery 命名空間下只宣告一個名稱;
2. 接受 options 參數以控制外掛行為;
3. 對外暴露外掛的預設設定;
4. 適當地將子函式提供給外部呼叫;
5. 保持私有函式;
6. 支援元資料(metadata)外掛。
這代表它是一個獨立的腳本。若腳本含多個互補的外掛(如 $.fn.doSomething() 與 $.undoSomething()),可視情況宣告多個名稱;但一般情況建議用單一名稱統整所有細節。本例宣告一個叫 hilight 的名稱:
$.fn.hilight = function( options ){
// 這裡是外掛的實作程式碼
};
// 呼叫:$("divTest").hilight();
$.fn.hilight = function(options){
var defaults = { foreground : 'red', background : 'yellow' };
$.extend(defaults,options); //用傳入的 options 擴充預設值
};
// 使用:$('#myDiv').hilight({ foreground: 'blue' });
作為優化,應把預設值暴露出來,讓使用者用最少的程式碼就能自訂:
$.fn.hilight = function(options){
//第一個參數傳空物件,避免覆寫 defaults
var opts = $.extend({},$.fn.hilight.defaults,options);
}
$.fn.hilight.defaults = { foreground : 'red', background : 'yellow' };
// 使用者可這樣自訂:
$.fn.hilight.defaults.foreground = 'blue';
$('.hilightDiv').hilight();
可以將某些子函式(如格式化文字的 format)對外開放,讓使用者擴充:
$.fn.hight = function(options){
return this.each(function(){
var $this = $(this);
var markup = $this.html();
markup = $.fn.hilight.format(markup);
$this.html(markup);
});
};
$.fn.hilight.format = function(txt){ return '<strong>' + txt + '</strong>'; };
一旦對外暴露就得考慮後續維護,若沒把握,寧可不開放。要定義不對外公開的函式,可用閉包:
(function($){
$.fn.hilight = function(options){ debug(this); /*...*/ };
function debug($obj){
if(window.console && window.console.log){ window.console.log('hilight selection count :' + $obj.size()); }
}
})(jQuery);
如此一來,debug 就無法在閉包外被呼叫。
支援 metadata 能讓設定寫在標籤中,寫 demo 時特別方便,實作也很容易:
$.fn.hilight = function(options){
var opts = $.extend({},$.fn.hilight.defaults,options);
return this.each(function(){
var $this = $(this);
var o = $.meta ? $.extend({},opts,$this.data()) : opts;
//完成支援元資料
});
}
// 標籤中設定:
// <div class="hilight { background: 'red', foreground: 'white' }">Have a nice day!</div>
(function($){
$.fn.hilight = function(options){
debug(this);
var opts = $.extend({}, $.fn.hilight.defaults, options);
return this.each(function(){
$this = $(this);
var o = $.meta ? $.extend({}, opts, $this.data()) : opts;
$this.css({ backgroundColor: o.background, color: o.foreground });
var markup = $this.html();
});
}
function debug($obj){
if(window.console && window.console.log){ window.console.log('hilight selection count: ' + $obj.size()); }
};
$.fn.hilight.format = function(txt){ return '<strong>' + txt + '</strong>'; };
$.fn.hilight.defaults = { foreground : 'red', background : 'yellow' };
})(jQuery);
轉載請註明出處 https://samlin.cnblogs.com。也建議開發外掛時把方法開放出來:
return { method1: function(){}, method2: function(){} }
這樣使用時就能:
var plugin = $("<div/>").plugin();
plugin.method1();
plugin.method2();