1

I am getting the wrong filename in the following code. I'm sure its obvious what the mistake is but i dont see it. I get the correct amount of errors however all the filename are the same rather then the filename in error.

for(var i=0; i<this.files.length; ++i){
    var f = this.files[i];
    var reader = new FileReader();
    reader.onload = function(e) {
        if(e.total>maxFilesize){
            tooBigFilesLs.push(f.name);
0

2 Answers 2

2

Javascript Closures

There is just an example about it in that article in "Creating closures in loops: A common mistake"

Try with this:

for(var i=0; i<this.files.length; ++i){
    var f = this.files[i];
    var reader = new FileReader();

    (function(name){

        reader.onload = function(e) {
            if(e.total>maxFilesize){
                    tooBigFilesLs.push(name);
        }
    }
     }(f.name));
}

(not tested)

Basically, when you define that function on 'onload', you are creating a closure, and all the functions you create in that loop share it, so all the functions has access to 'f' and 'reader', so 'f' will remain pointing to the last file in the loop. Adding the anonymous closure in my example, using that 'name' parameter, you ensure that the function in the 'onload' gets the right name.

Sign up to request clarification or add additional context in comments.

2 Comments

The reader outside of the func bothers me. Will that work? i end up writing for(var i=0; i<this.files.length; ++i){ var f = this.files[i]; (function(f){...})(f); before you pasted your code. That definitely does work. BTW your link explained it clearly
Well, I don't know what is that FileReader object, but probably is good idea to put it inside of the closure, as I understand you want to create one per file.
2

I think this is a closure issue with your for loop.

Here is an example of how to handle it.

// Basic idea...

reader.onload  = (function(value) {
    return function() {
        alert(value);
    }
})(f.name);

2 Comments

Actually, i dont pass the value into reader.onload. Or at least i dont know how to. The other answer clearly shows me the solution (i read the link before he pasted code)
I show you the basic solution which solves the problem. You just have to plug your logic in. Sorry I didn't do all the work for you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.