开发者

Incorrect variable when calling callback in JS

开发者 https://www.devze.com 2023-04-04 11:28 出处:网络
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 filena开发者_JS百科me are the sam

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 filena开发者_JS百科me 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);


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.


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);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号