0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

window.matchMediaとAbortControllerでリスナ登録の制御をする

0
Posted at

メモ

'use strict';

  /*** 
  * 最初に特定のmediaQueryの範囲内でのみ実行させたい処理を定義 
  * 
  */
  // PC版の幅のみ実行させたい
  const hogeFuncPC01 = () => {
    console.log('hogeFuncPC-01が実行されました');
  };
  // const hogeFuncPC02 = () => {
  //   console.log('hogeFuncPC-02が実行されました');
  // };

  // SP版の幅のみ実行させたい
  const hogeFuncSP01 = () => {
    console.log('hogeFuncSP-01が実行されました');
  };
  // const hogeFuncSP02 = () => {
  //   console.log('hogeFuncSP-02が実行されました');
  // };

  

  /*** 
  * 処理実行を希望するmediaQueryの範囲内(true)で呼び出す関数と、mediaQueryの範囲外(false)で呼び出す関数を定義
  */
  
  // AbortControllerのsignal格納用
  let controllerPC = null;
  let controllerSP = null;
  
  // (このファイル上で実験的に試用)resizeイベントの登録と解除の関数を設定
  
  controllerPC = new AbortController();
  controllerSP = new AbortController();
  

  const funcsPC= () => {
    // SP用イベントを解除
    controllerSP?.abort();
    controllerSP = null;

    // PC用イベントの二重登録を防止
    controllerPC?.abort();

    // 新しいControllerを作成
    controllerPC = new AbortController();
    
    // add
    window.addEventListener('resize', hogeFuncPC01, { signal: controllerPC.signal });
    // window.addEventListener('resize', hogeFuncPC02, { signal: controllerPC.signal });

  }
  const funcsSP = () => {
    // PC用イベントを解除
    controllerPC?.abort();
    controllerPC = null;

    // SP用イベントの二重登録を防止
    controllerSP?.abort();

    // 新しいControllerを作成
    controllerSP = new AbortController();
    // add
    window.addEventListener('resize', hogeFuncSP01, { signal: controllerSP.signal });
    // window.addEventListener('resize', hogeFuncSP02, { signal: controllerSP.signal });
  }

  /*** 
  * どのような条件下で関数呼び出しをするかをまとめる
  */
  const windowWidth = '(width <= 767px)';
  const mql = window.matchMedia(windowWidth);

  const mqlFuncA = (e) => { 
    if (e.matches) {
      // 希望するmediaQueryの範囲内だった場合に呼び出す処理
      // 767px以下
      console.log('767px以下');
      funcsSP();
    } else {
      // 希望するmediaQueryの範囲外にだった場合に呼び出す処理
      // 767pxより大きい
      console.log('767pxより大きい');
      funcsPC();
      
    }
  }

  // 範囲内外問わず、ページ読み込み時に実施される処理
  mqlFuncA(mql);

  // changeイベント発生時に呼び出される処理
  mql.addEventListener('change', mqlFuncA);
0
0
0

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?