Home > Mobile >  JavaScript/TypeScript - Callback not removed, why?
JavaScript/TypeScript - Callback not removed, why?

Time:10-02

Colleagues, I can prove with logs that removing listener in some public component does not work. First, I see the listener is still called, second, I never see second console output, which puzzles me even more.

const scanListeners = []
...
function removeListener(callback) {
    console.log("About to remove listener")
    scanListeners = scanListeners.filter(listenerCallback => listenerCallback !== callback)
    console.log("Listener removed")
}

Could this be explained with some JavaScript specifics? I am not a huge expert in JS but still some years of work and I still cannot explain what happens.

BTW the component is invoked in ReactNative environment, like this:

const listener: Component.callBack = (code) => {
    processCode(code)
    dispatch(fetchList(code));
    try {
      Component.removeListener(listener);
    }
    catch { }
  };

P.S. Listener adding code:

function addScanListener(callback) {
  const listenerAlreadyExists = scanListeners.some(listenerCallback => listenerCallback === callback)
  if (!listenerAlreadyExists) {
      scanListeners.push(callback)
  }
}

CodePudding user response:

const scanListeners = []
...
function removeListener(callback) {
    console.log("About to remove listener")
    scanListeners = scanListeners.filter(listenerCallback => listenerCallback !== callback)
    console.log("Listener removed")
}

In this this case you are trying to reassign const variable. More about Scope.

  • Related