Adding and removing event listeners with argument bearing functions

While the currying is nice, it means that it returns a new function each time it is called, rather than a copy of the same function. You need to somehow hold a reference to the function that is being bound, and then use it when removing the event listener. Without the context of the rest of your code I will attempt to pseudo-code it a bit below:

const eventMap = new Map();

function getMapKey(i, j) {
    return `${i},${j}`;
}

function addEvents() {
    for (let i = 0; i < 11; i++) {
        for (let j = 0; j < 11; j++) {
            if ((i > 1 && i < 9 && j > 1 && j < 9) && checkCorners(i, j) === true) {
                let ball = document.getElementById(i.toString() + j.toString());
                let removeBallFn = removeBall(i, j);
                let key = getMapKey(i, j);
                eventMap.set(key) = removeBallFn;
                ball.addEventListener('click', removeBallFn);
            }
        }
    }
}

function removeEvents() {
    for (let i = 0; i < 11; i++) {
        for (let j = 0; j < 11; j++) {
            if ((i > 1 && i < 9 && j > 1 && j < 9) && checkCorners(i, j) === true) {
                let ball = document.getElementById(i.toString() + j.toString());
                let key = getMapKey(i, j);
                let removeBallFn = eventMap.get(key) = removeBallFn;
                ball.removeEventListener('click', removeBallFn);
                eventMap.delete(key);
            }
        }
    }
}

This is untested as I don't have the rest of your code. The principle is that each time we generate a "remove" function, we store it in the Map (eventMap here) using a unique key based on a concatenation of the i and j values at that point in the loop. Then, when we got to remove, pull the same "remove" function out of the map using the same key, and pass it to removeEventListener. There are other ways to do this-- this is just one option. Adjust as needed given the larger context of your code. Hopefully this works for you!

Tags:

Javascript