简体   繁体   中英

Memory leak with addeventlistener()

I have a modal box which opens on a button click, when the modal is visible, if the area outside the content box is clicked, then the modal should disappear.

The issue i'm having is that my modal keeps creating the modal and not being completely removed, thus creating a memory leak.

The class show-login-modal handles the visibility of the modal.

let x = 1;

function LoginPopup(){

    let modal = document.getElementById('modal');

    modal.classList.add('show-login-modal');

    let xx = x++;

    function _removeModal() {
        modal.classList.remove('show-login-modal');
        modal.removeEventListener("click", this);
    }

    modal.addEventListener('click', function(event) {
        console.log(xx);
        if (event.target === modal) {
            _removeModal();
         } 
     });
}

I included the console.log for reference.

What is the best way to fix this?

removeEventListener is being used incorrectly, it needs to be invoked with a named function. So, in your case, you'd want to move the event target detection inside of _removeModal

function _removeModal(event){ if (event.target === this){ ... modal.removeEventListener('click', _removeModal)} }

modal.addEventListener('click', _removeModal)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM