LoginSignup
1
0

More than 3 years have passed since last update.

まとめてremoveEventListenerする

Last updated at Posted at 2021-03-19

ターゲットにイベントリスナーを登録/解除する

クラス定義
/**
 * イベントマネージャー
 */
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');
// >> 
1
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0