-1

So I have a multifile uploader I'm working on and I have trouble maintaining the i form the for loop. Basically the problem is that I pass the i value in the progressHandler function but everytime the progressHandler fires it fires with the last i value which would be files.files.length.

What is the best way to keep the i value passed in the first place?

for (var i = 0; i < files.files.length; i++) {
    ...
    var ajax = new XMLHttpRequest();
    ajax.upload.addEventListener("progress", function(event){progressHandler(event,i)}, false);
    ajax.addEventListener("load", function(event){completeHandler(event,i)}, false);
    ...
}
Matthew Abrman
  • 711
  • 10
  • 18
  • you need to use a closure, there are many examples for that, one of them: http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example – A. Wolff Mar 04 '14 at 15:19

1 Answers1

0

You need to capture i in a closure, check out here for a good guide on using them. Something like this:

for (var i = 0; i < files.files.length; i++) {
    ...
    (function (i) {
        var ajax = new XMLHttpRequest();
        ajax.upload.addEventListener("progress", function(event){progressHandler(event,i)}, false);
        ajax.addEventListener("load", function(event){completeHandler(event,i)}, false);
    }
    ...
}
Dutts
  • 5,781
  • 3
  • 39
  • 61