0

I have been searching for how to remove a previous event listener from a button and have found many solutions, but they haven't been working for me as I believe I have slightly different situations.

Assume the button has been clicked prior and I am clicking it sometime after the first. name is a value being typed in by the user, so it can change as many times as the user decides. I've snipped out unnecessary code segments for this issue, but this is the gist of it.

Below is what I am trying to get working:

var prevTutor = null;

const sendInvite = (name) => {
    // ...
}

some_function() {

    name = { user_input }

    if (prevTutor) {
        inviteBtn.removeEventListener('click', function() {
            sendInvite(prevTutor);
        });
    }

    prevTutor = name;

    inviteBtn.addEventListener('click', function() {
        sendInvite(name);
    });
}

I've seen this, and tried this, working with passing in a function that takes 0 parameters, but my function that I am trying to add as an event listener takes a parameter and I don't know if there is any way exactly to remove it this way. If there is, I haven't seem to have found the solution.

jakewags01
  • 41
  • 4

1 Answers1

1

You need to keep the reference to the exact same function passed to addEventListener, so move the event handler function outside some_function and make it a named function.

function inviteClickHandler(e) {
    sendInvite(name); // you may need to conditionally change the name
}
function some_function() {
    // remove event listener like so:
    inviteBtn.removeEventListener('click', inviteClickHandler);
    // and add it like so:
    inviteBtn.addEventListener('click', inviteClickHandler);
}
Unmitigated
  • 76,500
  • 11
  • 62
  • 80