jQuery 插件開發面臨:命名衝突、參數合併、實例管理、鏈式調用、公私有方法區分、AMD/CommonJS 模組化等問題。jQuery Boilerplate 提供了一個經過社區驗證的基礎模板,解決上述通用問題,而非限定具體業務邏輯。
;(function($, window, document, undefined) {
// 1. 防止前文遺漏分號導致合併報錯
// 2. 將全局對象作為參數傳入,縮短作用域鏈查找,壓縮時可縮短變量名
// 3. undefined 參數防止 ES3 被篡改(ES5+ 已不可寫)
var pluginName = 'myPlugin', // 插件名,用於數據鍵名、命名空間
defaults = { // 默認配置
propertyName: 'value',
onInit: null,
onDestroy: null
};
// 構造函數
function Plugin(element, options) {
this.element = element; // DOM 元素引用
this.settings = $.extend({}, defaults, options); // 深度合併:默認值 + 用戶傳參
this._defaults = defaults;
this._name = pluginName;
this.init();
}
// 原型方法:公共 API 與內部邏輯
$.extend(Plugin.prototype, {
init: function() {
// 初始化邏輯:綁定事件、創建子元素、調用回調
if (typeof this.settings.onInit === 'function') {
this.settings.onInit.call(this.element, this);
}
console.log('Plugin initialized:', this._name);
},
yourMethod: function(arg) {
// 業務方法,可鏈式調用
return this; // 支援鏈式
},
destroy: function() {
// 清理:解綁事件、移除數據、銷毀子元素
this.element.removeData('plugin_' + pluginName);
if (typeof this.settings.onDestroy === 'function') {
this.settings.onDestroy.call(this.element, this);
}
}
});
// 輕量級封裝:防止重複實例化,支援鏈式調用
$.fn[pluginName] = function(options) {
return this.each(function() {
// 單例模式:每個元素只實例化一次
if (!$.data(this, 'plugin_' + pluginName)) {
$.data(this, 'plugin_' + pluginName, new Plugin(this, options));
}
});
};
})(jQuery, window, document);
| 設計點 | 實現方式 | 作用 |
|---|---|---|
| IIFE 隔離作用域 | (function($, window, document, undefined){...})(jQuery, window, document) | 避免全局污染,參數局部化提升查找速度與壓縮率 |
| 分號前綴 | ; 開頭 | 防止合併壓縮時前一文件缺分號導致語法錯誤 |
| 默認配置合併 | $.extend({}, defaults, options) | 不修改原默認對象,用戶參數覆蓋默認值 |
| 實例單例化 | $.data(this, 'plugin_' + pluginName) | 同一元素多次調用插件不重複創建實例 |
| 鏈式調用支援 | return this; 在 $.fn[pluginName] 中 | 保持 jQuery 鏈式風格:$('.el').plugin().css(...) |
| 數據綁定 | $.data() 存儲實例引用 | 可隨時獲取實例調用公共方法:$.data(el, 'plugin_xxx').publicMethod() |
$.Widget(jQuery UI 核心),提供完整生命周期(_create, _init, _destroy)、事件觸發(_trigger)、選項管理(option 方法)、主題滾動等。適合狀態複雜、需高度擴展的組件(如 Datepicker, Dialog)。$.fn.namespace.pluginName 避免同名衝突,適合大型團隊多插件共存。;(function($, window, document, undefined) {
var pluginName = 'tooltip',
defaults = { content: '提示文字', position: 'top', delay: 200 };
function Plugin(element, options) {
this.element = element;
this.settings = $.extend({}, defaults, options);
this._name = pluginName;
this._timeout = null;
this.init();
}
$.extend(Plugin.prototype, {
init: function() {
var $el = $(this.element);
$el.on('mouseenter.' + pluginName, $.proxy(this.show, this));
$el.on('mouseleave.' + pluginName, $.proxy(this.hide, this));
},
show: function() {
clearTimeout(this._timeout);
this._timeout = setTimeout(() => {
this.$tip = $('' + this.settings.content + '').appendTo('body');
this.position();
this.$tip.fadeIn(150);
}, this.settings.delay);
},
hide: function() {
clearTimeout(this._timeout);
if (this.$tip) {
this.$tip.fadeOut(150, () => this.$tip.remove());
this.$tip = null;
}
},
position: function() {
var $el = $(this.element), pos = $el.offset(), h = $el.outerHeight(), w = $el.outerWidth();
var tip = this.$tip, th = tip.outerHeight(), tw = tip.outerWidth();
var top, left;
switch (this.settings.position) {
case 'top': top = pos.top - th - 5; left = pos.left + w/2 - tw/2; break;
case 'bottom': top = pos.top + h + 5; left = pos.left + w/2 - tw/2; break;
// left/right ...
}
tip.css({ top: top, left: left });
},
destroy: function() {
$(this.element).off('.' + pluginName);
this.hide();
this.element.removeData('plugin_' + pluginName);
}
});
$.fn[pluginName] = function(options) {
return this.each(function() {
if (!$.data(this, 'plugin_' + pluginName)) {
$.data(this, 'plugin_' + pluginName, new Plugin(this, options));
}
});
};
})(jQuery, window, document);
// 基礎調用
$('.btn').tooltip({ content: '這是提示', position: 'bottom' });
// 獲取實例調用公共方法
var api = $('.btn').data('plugin_tooltip');
api.destroy(); // 銷毀
// 鏈式
$('.btn').tooltip().css('color', 'red');
jQuery Boilerplate 不是銀彈,但提供了「不重複造輪子」的工業級起點。掌握其核心模式(IIFE、單例數據綁定、配置合併、鏈式返回、銷毀清理),即可快速產出高質量、可維護、符合社區規範的 jQuery 插件。現代項目若使用 Vue/React,建議直接開發組件而非 jQuery 插件,但理解此模式對維護舊專案、編寫框架無關的工具庫仍極有價值。