samedi 24 février 2018

How to delete event listener without external function

Got the real dilemma. I have an init function which has lots of parameters inside which are depended on each other and can't be remove outside, an array of elements and added to each a click event listener. This event listener checks if the clicked element is a certain element then remove the click listener from all elements in the array. The promblem is I have to use an anonimus function in the event listener due to the internal parameters of the init function, but to delete an event listener I must pass the same function in removeEventListener so it must be named function and I can't get solution for this.

The approximate logic:

let init = () =>{

  //some internal parameters here and logic

  for (let i = 0; i < elArr.length; i++) {

    elArr[i].addEventListener('click', event => {
        if (event.target.style.background ===
            elArr[pickedElement].style.background) {

            //Not working (can't define the param as a separate function due 
            //to params of this function can't be passed to there)
            for (let i = 0; i < elArr.length; i++)
                elArr[i].removeEventListener("click", event);

        } else {
            event.target.style.background = bgColor;
        }
    });  
}




Aucun commentaire:

Enregistrer un commentaire