jQuery 的plugin開發需要注意的事情,
1. 明確jQuery的命名空間只有一個。
2. 明白options參數用來控制plugin的行為。
3. 為預設的plugin設定提供公用的存取權限。
4. 為子函數提供公用的存取權限。
5. 私人的函數絕對是私人訪問
6. 支援metadata plugin。
我將會在下面的例子中一個一個的說明上面這幾個條件,做完這些事情後我們就會建立一個高亮顯示text的簡單外掛程式。
1. 明確jQuery的命名空間只有一個
在我們的例子裡,我們將會命名這個外掛程式名字為hilight,
也就是我們的plugin可以通過下面的方法來使用:
為什麼jQuery的plugin只有一個命名空間?可能是設計的要求,或者是這樣的話可讀性更強,亦或是為了物件導向的設計模式。
2.明白options參數來控制plugin的行為。
讓我們先為我們的hilight外掛程式明確一下foreground和background的顏色。我們應該能夠允許這兩個option作為option對象傳遞給plugin的主函數。例如:
現在外掛程式能夠設定如下的屬性:
3. 為預設的plugin設定提供公用的存取權限。
我們這裡可以改進一下,就是讓上面的代碼能夠設定能夠擴充。這樣當使用這個外掛程式的使用者能夠使用最少的代碼重載我們的option。這也就是我們開始使用function對象的好處。
現在使用者可以在他們的script中使用一行代碼來設定foreground屬性:
有了上面的代碼我們就可以把某個DOM控制項的foregrounf顏色設定為blue了。
4. 為子函數提供公用的存取權限
這個條款和上面的相仿,能很有趣的讓你的Plugin有擴充功能。例如:在lilight的plugin中我們能夠定義一個function是format,可以定義hilight的text的形式。我們的plugin代碼將會顯示如下:
這裡我們可以很容易支援另外的一個option對象來通過一個callback 函數來重載預設的formatting。那將會是另外一個不錯的支援自訂的方式。
5. 私人的函數絕對是私人訪問
公開plugin的一些Option能夠被自訂當然是個非常強大的功能。但是你需要考慮哪部分應該被公開,哪部分不應該通過外部存取,否則會破會你已經封裝好的結果。
這裡debug方法不能從外部存取,因為他在plugin的展現中屬於私人的方法。
6.支援metadata plugin。
使用Metadata Plugin需要看你的plugin是什麼類型,可能它會使你的外掛程式功能更加強大。個人來說,我比較喜歡metadata plugin是因為它能偶讓我的plguin的option通過標記重載。
如果metadata plugin能夠成功的封裝到我們的外掛程式,那麼可以通過下面的標記來使用這個lilight外掛程式。
最終代碼如下:
複製代碼 代碼如下://
// create closure
//
(function($) {
//
// plugin definition
//
$.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);
});
};
//
// private function for debugging
//
function debug($obj) {
if (window.console && window.console.log)
window.console.log('hilight selection count: ' + $obj.size());
};
//
// define and expose our format function
//
$.fn.hilight.format = function(txt) {
return '<strong>' + txt + '</strong>';
};
//
// plugin defaults
//
$.fn.hilight.defaults = {
foreground: 'red',
background: 'yellow'
};
//
// end of closure
//
})(jQuery);