Need technical code explanation

Found this code for previewing an image after selecting it in a file input element.

$(document).ready(function(e) {
  $('#image-input').change(function(){
    let reader = new FileReader();
    reader.onload = (e) => { 
      $('#preview-image-before-upload').attr('src', e.target.result); 
    }
    reader.readAsDataURL(this.files[0]); 
  });
});

I’m curious about the implications of the way it is implemented. The code creates a new reader and an onload listener for it every time the file input changes.

It seems that the listener on the reader doesn’t get removed even after the change listener on the #image element finishes, because the onload listener asynchronous(?).

Does that mean this code will leave a bunch of dangling listeners for however many times the file input changes values?

Nevermind - found the answer: Stackoverflow

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.