Question

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);
    ...
}
Was it helpful?

Solution

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);
    }
    ...
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top