初次開發 jQuery 外掛時,往往不知從何下手。照著官方格式寫雖然可行,卻常常不夠完善,一不小心就做出難維護、難擴展、效能差的「爛」外掛。而當你累積經驗後又會發現新問題:在眾多開發模式中,究竟哪一種最好?本文介紹一個實務上常用的基礎模板——jQuery Boilerplate。
jQuery Boilerplate 並未提供各種模式的完美解方,它的目標只是提供一個最基礎的模板,讓初學者能在其上做相應修改。值得一提的是,bootstrap 採用的正是這個模式。
模板開頭用一個分號防止與其他不規範外掛合併時出問題;把 window、document、undefined 作為形參傳入,既避免 ES3 中 undefined 被改寫,也藉由作用域縮短查找路徑來提效:
;(function ( $, window, document, undefined ) {
var pluginName = "defaultPluginName",
defaults = { propertyName: "value" };
function Plugin ( element, options ) {
this.element = element;
this.settings = $.extend( {}, defaults, options );
this._defaults = defaults;
this._name = pluginName;
this.init();
}
$.extend(Plugin.prototype, {
init: function () { console.log("xD"); },
yourOtherFunction: function () { /* some logic */ }
});
$.fn[ pluginName ] = function ( options ) {
this.each(function() {
if ( !$.data( this, "plugin_" + pluginName ) ) {
$.data( this, "plugin_" + pluginName, new Plugin( this, options ) );
}
});
return this;
};
})( jQuery, window, document );
這個輕量級模板已能滿足大部分需求:物件只實例化一次、支援鏈式呼叫、預設參數,以及公有與私有方法的呼叫。
在規模較大的元件開發中,還會面臨命名空間衝突、可擴展性、公有方法呼叫等問題。對此 jQuery Boilerplate 也提供了幾種模式:
· 輕量級(基礎)模式:適合初學者的通用起點。
· Widget factory 工廠模式:jQuery UI 的典型模式,用物件導向建構複雜有狀態的元件。
· Widget factory + RequireJS:為工廠模式加上 AMD 模組化載入支援。
· Namespaced pattern 命名空間模式:避免與其他外掛衝突。
你可以依專案規模與個人喜好,挑一個最合適的來用。