jQuery 事件命名空間允許為同一事件類型(如 `click`)綁定多個互不干擾的處理函數,通過「事件類型.命名空間」語法實現模塊化管理:
// 綁定
$(element).on('click.pluginA', handlerA); // 插件 A 的點擊
$(element).on('click.pluginB', handlerB); // 插件 B 的點擊
$(element).on('click', handlerCommon); // 通用點擊 (無命名空間)
// 觸發
$(element).trigger('click'); // 觸發所有 click (含 pluginA, pluginB, 通用)
$(element).trigger('click!'); // 僅觸發無命名空間的 click
$(element).trigger('click.pluginA'); // 僅觸發 pluginA 命名空間
$(element).trigger('click.pluginB'); // 僅觸發 pluginB 命名空間
<div style="width:100px;height:50px;background:#888;color:white;">test</div>
<button>根據命名空間觸發事件</button>
<script>
$('div').on('click', function() {
$('body').append('click 事件 (無命名空間)
');
});
$('div').on('click.plugin', function() {
$('body').append('click.plugin 事件
');
});
$('button').click(function() {
// 關鍵:click! 觸發無命名空間
// click 觸發所有
// click.plugin 觸發特定命名空間
$('div').trigger('click!');
});
</script>
| 語法 | 綁定時含義 | 觸發時含義 |
|---|---|---|
click | 基礎事件,無命名空間 | 觸發所有 click (含所有命名空間) |
click.foo | 屬於 foo 命名空間 | 僅觸發 foo 命名空間 |
click.foo.bar | 屬於 foo 和 bar 兩個命名空間 | 觸發同時屬於 foo 和 bar 的處理器 |
click! | 無效 (綁定時不可用 !) | 僅觸發無命名空間的處理器 |
// 插件 A
$.fn.pluginA = function() {
return this.on('click.pluginA', function() { /* ... */ })
.on('keydown.pluginA', function() { /* ... */ });
};
// 插件 B
$.fn.pluginB = function() {
return this.on('click.pluginB', function() { /* ... */ });
};
// 使用:互不干擾
$('#elem').pluginA().pluginB();
// 銷毀插件 A 事件,不影響 B
$('#elem').off('.pluginA');
const ModuleManager = {
modules: new Map(),
register(name, handlers) {
// handlers: { 'click': fn, 'keydown.ctrl': fn }
Object.entries(handlers).forEach(([event, fn]) => {
$(document).on(`${event}.module.${name}`, fn);
});
this.modules.set(name, handlers);
},
unregister(name) {
$(document).off(`.module.${name}`);
this.modules.delete(name);
}
};
// 使用
ModuleManager.register('analytics', {
'click': trackClick,
'submit.form': trackForm
});
ModuleManager.unregister('analytics'); // 乾淨卸載
// 測試時只觸發特定模塊的事件
function testAnalyticsClick() {
// 只觸發 analytics 模塊的 click,不觸發 UI、表單驗證等
$('#btn').trigger('click.module.analytics');
}
class Dropdown {
constructor($el) {
this.$el = $el;
this.ns = `.dropdown.${Date.now()}`; // 唯一命名空間
this.bind();
}
bind() {
this.$el.on(`click${this.ns}`, '.trigger', () => this.toggle());
$(document).on(`click${this.ns}`, (e) => {
if (!this.$el.is(e.target) && this.$el.has(e.target).length === 0) {
this.close();
}
});
}
destroy() {
this.$el.off(this.ns);
$(document).off(this.ns);
}
}
// 輕量級事件總線 (無 jQuery 依賴)
class EventBus {
constructor() {
this.handlers = new Map(); // eventName -> Set(handler)
}
on(event, handler) {
if (!this.handlers.has(event)) this.handlers.set(event, new Set());
this.handlers.get(event).add(handler);
}
off(event, handler) {
this.handlers.get(event)?.delete(handler);
}
emit(event, data) {
this.handlers.get(event)?.forEach(h => h(data));
}
// 命名空間模擬
onNamespaced(event, namespace, handler) {
this.on(`${event}:${namespace}`, handler);
}
offNamespaced(event, namespace, handler) {
this.off(`${event}:${namespace}`, handler);
}
emitNamespaced(event, namespace, data) {
this.emit(`${event}:${namespace}`, data);
}
emitAllNamespaces(event, data) {
this.emit(event, data); // 基礎事件
// 可選:遍歷所有命名空間
}
}
jQuery 事件命名空間是解決大型應用中事件管理混亂的關鍵機制。核心語法:event.namespace 綁定,trigger('event.namespace') 精確觸發,off('.namespace') 批量清理。理解其「綁定時分類、觸發時過濾」的設計思想,對設計現代事件系統同樣有指導意義。