简体   繁体   中英

Passing arguments to callback functions

How can I pass parameters to an arrow function when an eventListener is triggered?

// Name of certificate
let certificateName = document.querySelector('.js--c-name').value;

// Call upload function
currentFileInput.addEventListener('change', fileUpload , false);

const fileUpload = (certificateName) = (evt) => {
  // Here I need the parameter certificateName for testing
  console.log(`Name of Certificate: #{certificateName}`);

  // Function stuff...
  let myFile = evt.target.files[0],
      maxFileSize = evt.target.getAttribute('data-fileSizeMax');

  // Check filesize
  if(myFile.size <= maxFileSize){
   // etc.
  }

}

Make your fileUpload to return the inner function

const fileUpload = (certificateName) => (evt) => {

  console.log(`Name of Certificate: #{certificateName}`);

  let myFile = evt.target.files[0],
      maxFileSize = evt.target.getAttribute('data-fileSizeMax');

  if(myFile.size <= maxFileSize){
   // etc.
  }

}

You need to call the fileUpload function and pass certificateName .

currentFileInput.addEventListener('change', fileUpload(certificateName), false);

You need to wrap the function call in another function

let certificateName = document.querySelector('.js--c-name').value;

currentFileInput.addEventListener('change', function(e){
  fileUpload(e, certificateName ); //observe changes in this line
}, false);

const fileUpload = (evt, certificateName) => { //pass the arguments 
  //rest of your code as is    
}

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