1

The removeEventListener will not work here because the functions are referring to an anonymous function:

const startSelectNode = (stepIndex) => {
  document.addEventListener("click", (e) => onClick(e, stepIndex), true);
};

const stopSelectNode = (stepIndex) => {
  document.removeEventListener("click", (e) => onClick(e, stepIndex), true);
};

But I can't name the function here because it requires stepIndex which is a local var. How can I make this work?

2 Answers 2

3

Yair Cohen's answer has the right idea, but it's missing something. addEventListener requires a function reference and not a function call. In his code, onStepIndex will get executed once and then never again.

To create a function reference and be able to feed it parameters and be able to remove the event listener later, you could use the concept called currying.

const onStepIndex = function(stepIndex) {
    return function actualOnStepIndex(event) {
        console.log(event);
        console.log(stepIndex);
    }
}
const handlers = [];

const startSelectNode = (stepIndex) => {
  document.addEventListener("click", handlers[stepIndex] = onStepIndex(stepIndex), true);
};

const stopSelectNode = (stepIndex) => {
  document.removeEventListener("click", handlers[stepIndex], true);
};

startSelectNode(1); // This adds the event listener  for stepIndex = 1
stopSelectNode(1); // This removes the event listener for stepIndex = 1

Basically, by calling onStepIndex you return the actual function, which is now the event handler. We saved the reference to the function in the handlers array and we need that reference if we later want to call removeEventListener.

Sign up to request clarification or add additional context in comments.

Comments

2

You can definitely name the function, you just have to do it outside of the function's scope, like this:

function onStepIndex(e, stepIndex) {
 // your action here
}

const startSelectNode = (stepIndex) => {
  document.addEventListener("click", onStepIndex(e, stepIndex), true);
};

const stopSelectNode = (stepIndex) => {
  document.removeEventListener("click", onStepIndex(e, stepIndex), true);
};

1 Comment

This is not how you pass a function reference of onStepIndex.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.