'Javascript adding a new event listener on local object

I have a script below, where I dynamically create an Element Node of type 'li'. This addMovieHandler() is called whenever the user clicks on a button.

Additionally, the newly addded list item should be deleted on 'click'.

So, what I experimented is I added an event Listener on the local object newLi and also passed that to the deleteMovieHandler() function.

And It Works. I added several list items and when I clicked any, it was gone from the screen.

const movieList = document.getElementById('movie-list');

const deleteMovieHandler = (newLi) => {
    newLi.style.display = 'none';
}

const addMovieHandler = (image) => {
    
    const newLi = document.createElement('li');
    newLi.className = 'movie-element';

    newLi.innerHTML = `
    <div class = "movie-element__image">
        <img src="${image}"></img>
    </div> `;

    newLi.addEventListener('click', deleteMovieHandler.bind(this, newLi));

    movieList.appendChild(newLi);
}

I get it that this is bad practice to just hide the element, which becomes a resource wastage.

But the center of interest is that there was a separate event listener on every list item, even though that local object should have been lost after function termination.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source