ターゲットにイベントリスナーを登録/解除する
クラス定義
/**
* イベントマネージャー
*/
class EventManager {
/**
* イベントマネージャーのコンストラクター
* @param {Element|Document|Window} node addEventListenerを持つオブジェクト
*/
constructor(node) {
this.node = node;
this.funcs = [];
}
/**
* イベントリスナー登録
* @param {string} type イベント名
* @param {Function} fn リスナー関数
*/
add(type, fn) {
this.funcs[type] ??= [];
this.funcs[type].push(fn);
this.node.addEventListener(type, fn);
}
/**
* イベントリスナー全解除
* @param {string} type イベント名
*/
removeAll(type) {
if (!this.funcs[type]) return;
for (let func; func = this.funcs[type].pop();) {
this.node.removeEventListener(type, func);
}
}
/**
* イベント発行
* @param {string} type イベント名
*/
dispatch(type) {
const event = new Event(type);
this.node.dispatchEvent(event);
}
}
使用方法
// window用のイベントマネージャーを作成
const windowEventManager = new EventManager(window);
// イベントリスナー登録
windowEventManager.add('hogehoge', _ => console.log(1));
windowEventManager.add('hogehoge', _ => console.log(2));
windowEventManager.add('hogehoge', _ => console.log(3));
// イベント発行
windowEventManager.dispatch('hogehoge');
// >> 1
// >> 2
// >> 3
// イベントリスナー全解除
windowEventManager.removeAll();
// イベント発行
windowEventManager.dispatch('hogehoge');
// >>