0

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.

mr.loop
  • 818
  • 6
  • 20
  • I don't think I'm quite understanding what you are asking. Yes, the event handler will still be there on the li element if you haven't removed it. So could you elaborate on the question a bit? And is there a reason for not removing the li element once it has been clicked? – A Haworth May 13 '22 at 15:01
  • @AHaworth I am curious why the passing `newLi` as argument still works when it has been overridden after function calls. My expectation was even if js is storing the element node on which event listener is applied, whenever I clicked any, only the last one would have been hidden. – mr.loop May 13 '22 at 15:04
  • 1
    newli is just a JS variable which has a scope, just within that function. It's not remembered as such by JS. You've created an li element and added an eventlistener to that li element and appended that li element to the list so that element is still around and still got its eventlistener attached. – A Haworth May 13 '22 at 15:11
  • @AHaworth So, the argument to the element's event listener is also decided when we created the listener? I just wanted a brief flow of what's happeniing here. – mr.loop May 13 '22 at 16:31
  • JS is a pass by value language - the examples here might help: https://stackoverflow.com/questions/518000/is-javascript-a-pass-by-reference-or-pass-by-value-language Of course, the value that is being passed might itself be a reference (in this case to an element). – A Haworth May 13 '22 at 18:02

0 Answers0