Home > OS >  I need help to understand why my modal is making multiple eventlisteners if it's closed then op
I need help to understand why my modal is making multiple eventlisteners if it's closed then op

Time:01-13

OK so i make a modal in which i insert the options to alter the card properties like name, description and company. It's actually working fairly well except that when i open another modal without refreshing the page it doubles (then triplicates and so on) the number of requests it sends. And i dont know why. I'll link a video of my screen just so i can make myself more clear.

https://www.veed.io/view/17448fc2-7068-4419-87a2-395c528bbffa?sharingWidget=true&panel=share

here's the part of my code i think is important

function getAllDepartmentHandleButton() {
    const allDeleteButtons = document.querySelectorAll('.departmentContainer__content--card')

    allDeleteButtons.forEach(e => {
        e.addEventListener('click', (event) => {

            //console.log(event)
           
            if(event.target.classList.value == 'remove') {
                showRemoveDepartmentModal(event.target.id, event.target.alt)
            } else if(event.target.classList.value == 'edit') {
                showEditDepartmentModal(event.target.id)
            }
        })
    })
}

async function showEditDepartmentModal(departmentId) {
    let companyToEditid = 0
    const allDepartments = await getAllDepartments()
    const editModal = document.querySelector('.editDepartmentModal')
    const closeBtn = document.querySelector('.editDepartmentModal__container > img')
    const nameInput = document.querySelector('.editDepartmentModal__container--departmentName')
    const descriptionInput = document.querySelector('.editDepartmentModal__container--departmentDescription')
    const selectedCompanyInput = document.querySelector('.editDepartmentModal__container--company > span')
    const placeToAppend = document.querySelector('.editDepartmentModal__container--list')
    const showCompanyOptionsButton = document.querySelector('.editDepartmentModal__container--company')
    const dialogCompanyOptions = document.querySelector('.editDepartmentModal__container > dialog')
    const allCompanies = await getAllCompanies()
    const buttonSaveAlterations = document.querySelector('.editDepartmentModal__container--button')

    allCompanies.forEach(e => {
        placeToAppend.insertAdjacentHTML('beforeend', `
    <li id="${e.uuid}">${e.name}</li>

    `)        
    })

    editModal.showModal()

    const selectedCompany = allDepartments.find(e => {
        if (e.uuid == departmentId) {
            return e
        }

    })

    closeBtn.addEventListener('click', () => {
        editModal.close()
    })

    nameInput.value = selectedCompany.name
    descriptionInput.value = selectedCompany.description
    selectedCompanyInput.innerText = selectedCompany.companies.name
    selectedCompanyInput.id = departmentId

    showCompanyOptionsButton.addEventListener('click', ()=> {
        if(dialogCompanyOptions.open) {
            dialogCompanyOptions.close()
        } else {
            dialogCompanyOptions.show()

        }
        
    })

    placeToAppend.addEventListener('click', (event) => {
        companyToEditid = event.target.id
        selectedCompanyInput.innerText = event.target.innerText
        dialogCompanyOptions.close()

    })

    buttonSaveAlterations.addEventListener('click', () => {
        if(nameInput.value == '' || descriptionInput.value == '') {
            alert('vazio')
        } else {

            editDepartmentFunction(nameInput.value, descriptionInput.value, companyToEditid)
            editModal.close()
        }
    })        
}


function editDepartmentFunction(test1, test2, test3) {
    console.log(test1, test2,test3)
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="../styles/globalStyles.css">
    <link rel="stylesheet" href="../styles/indexStyles.css">
    <link rel="stylesheet" href="../styles/AdminPageStyling copy.css">
    <link rel="stylesheet" href="../styles/adminPagesModal.css">
    
</head>
<body>
    <header>
        <div >
            <span><span >• </span>Kenzie Empresas</span>
            <button>Logout</button>
        </div>
    </header>

    <main>
        <div >
            <div >
                <span >Departamentos</span>
                <div >
                    <span >Selecionar Empresa</span>
                    <img src="../files/down-arrow-svgrepo-com.svg" alt="">
                </div>
                <dialog >
                    <ul>
                        
                    </ul>

                </dialog>
                
                <div ><img src="../files/plusIcon.svg" alt=""><span>Criar</span></div>
            </div>
            <div >

            </div>

            
        </div>

        <div >
            <div >
                <span >Usuários Cadastrados</span>                
            </div>

            <div >          

            </div>

            
        </div>
    </main>


    <dialog >
        <div >
            <img src="../files/closebtnsvg.svg" alt="">
            <span >Criar Departemento</span>
            <input type="text"  placeholder="Nome do Departamento">
            <input type="text"  placeholder="Descrição">
            <div >
                <span>Selecionar Empresa</span>
                <img src="../files/down-arrow-svgrepo-com.svg" alt="">
                
            </div>
            <dialog >
                <ul >                    

                </ul>
            </dialog>
            <span >Criar Departamento</span>
    
        </div>
    </dialog>
    
    <dialog >
        <div >
            <span>mensagem aqui</span>
            <div>Continuar</div>
            <img src="../files/closebtnsvg.svg" alt="">

        </div>
    </dialog>

    <dialog >

        <div >
            <dialog><ul ></ul></dialog>
            <img src="../files/closebtnsvg.svg" alt="">
            <span >Editar Departamento</span>
            <input type="text"  placeholder="Novo Nome do Departamento">
            <input type="text"  placeholder="Nova Descrição">
            <div >
                <span>Selecionar Empresa</span>
                <img src="../files/down-arrow-svgrepo-com.svg" alt="">
                
            </div>
            <dialog >
                <ul >                    
    
                </ul>
            </dialog>
            <span >Salvar Alterações</span>
    
        </div>
    </dialog>
    
</body>
<script src="../scripts/AdminPageScript.js"></script>
</html>

I tried literally everything but the only thing that actually made it stop was refreshing the page. Which, of course, is not a propper alternative

CodePudding user response:

You are adding event listeners in the same function(showEditDepartmentModal) you are using to show the modal.

You have two options. One, clear the event listeners when the modal closes. Two, add the event listeners outside of showEditDepartmentModal.

I would go with number two. Your showEditDepartmentModal is too big. Try to break it down into smaller parts. It's name is "showEditDepartmentModal" but it does more than that - not a great idea.

CodePudding user response:

You are adding event listener n times most probably, not only one time.

Option 1 (better):

Be sure addEventListener is called only one time, in document ready or something similar.

Option 2 (worse, use it if you can't use option 1):

Change this:

allDeleteButtons.forEach(e => {
    e.addEventListener('click', (event) => {

        //console.log(event)
       
        if(event.target.classList.value == 'remove') {
            showRemoveDepartmentModal(event.target.id, event.target.alt)
        } else if(event.target.classList.value == 'edit') {
            showEditDepartmentModal(event.target.id)
        }
    })
})

With something similar to this:

function clickFunction(event) {
    //console.log(event)
       
    if(event.target.classList.value == 'remove') {
        showRemoveDepartmentModal(event.target.id, event.target.alt)
    } else if(event.target.classList.value == 'edit') {
        showEditDepartmentModal(event.target.id)
    }
}

allDeleteButtons.forEach(e => {
    e.removeEventListener('click', clickFunction);
    e.addEventListener('click', clickFunction);
})
  • Related