0

Below is the code snippet used in one of the tutorials I am learning from now. Can someone please help to understand how an argument 'mediastate' can be passed to a variable 'transientListen' in the 'notify' function?

function createMediaListener(queries) {
  let transientListener = null;

  const keys = Object.keys(queries);

  const queryLists = keys.reduce((queryLists, key) => {
    queryLists[key] = window.matchMedia(queries[key]);
    return queryLists;
  }, {});

  const mediaState = keys.reduce((state, key) => {
    state[key] = queryLists[key].matches;
    return state;
  }, {});

  const notify = () => {
    if (transientListener != null) transientListener(mediaState);
  };

  const listeners = keys.reduce((listeners, key) => {
    listeners[key] = event => {
      mediaState[key] = event.matches;
      notify();
    };

    return listeners;
  }, {});

  const listen = listener => {
    transientListener = listener;
    keys.forEach(key => {
      queryLists[key].addListener(listeners[key]);
    });
  };

  const dispose = () => {
    transientListener = null;
    keys.forEach(key => {
      queryLists[key].removeListener(listeners[key]);
    });
  };

  const getState = () => mediaState;

  return { listen, dispose, getState };
}

export default createMediaListener;
Remco Haszing
  • 7,178
  • 4
  • 40
  • 83
esentai
  • 69
  • 1
  • 10
  • Apparently a *function* can be assigned to `transientListener`, making `transientListener` a… function. Which can be called with an argument. Hence the `!= null` check before; it's expected that `transientListener` either isn't set or is a function. – deceze Oct 05 '20 at 09:06

1 Answers1

0

How I understand, the "listen" function is called by return statement in the module. The problem is, "listen" function needs a parameter, otherwise is: transientListener = listener; => undefined.

lortschi
  • 2,768
  • 2
  • 18
  • 12