0

This is most likely something I'm overlooking but I can't figure out exactly what the issue is in this situation.

Upload: function (callback) {
    var formData, xhr, file,
    xhrLoaded = function () {
        if (callback) {
            callback(this.status, this.response, file);
        }
    };

    if (this._files.length < 1) {
        return false;
    }

    file = this._files.pop();
    while (file) {
        formData = new FormData();
        formData.append("file", file);

        xhr = new XMLHttpRequest();
        xhr.open("POST", this.options.uploadUrl);
        xhr.onload = xhrLoaded;
        xhr.send(formData);
        file = this._files.pop();
    }
}

Why is it the case that when the xhr onload event handler runs file is undefined? At first I thought it was because onload is getting called out of the current scope, but that didn't seem right based on my understanding of javascript scoping. So as a test I checked this on a simple page.

(function () {
    var test = "This is a test", testFunc = function () { console.log(test); };
    window.onload = testFunc;
})();

and the variable test has the correct value. This tells me it has something to do with the file variable changing. So tried to add var localFile = file to the xhrLoaded method to see if it would keep the correct value in that case but it doesn't appear to be the case.

MattMacdonald
  • 93
  • 1
  • 1
  • 9
  • I think the event is `onreadystatechange`. If `onload` is actually a thing and is compatible and equivalent (which makes sense) I’ve been doing this wrong forever. Anyways, did you try a `console.log(file);` before and after `xhr.send(formData);`? – Ry- Jan 16 '14 at 01:45
  • Onload is on the xhr2 spec I believe. A couple minutes after I posted I think I thought of what the issue is. I'll verify when I get a chance unless someone beats me to it. @minitech I have not tried that. I figured the send wouldn't destroy the object but I'll check if I come up empty on my hunch. – MattMacdonald Jan 16 '14 at 01:55
  • 1
    Similar http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example – Musa Jan 17 '14 at 14:44
  • @Musa I knew it was some problem like that but I couldn't remember the correct way to handle it. Returning a function was what I needed. I had fixed this another way yesterday but I'm going to switch it since this solution makes much more sense. I was aware of javascript's function scoping but I was tricking myself by not changing values and executing a function in different contexts to test. Anyway thanks for the link to an answer. – MattMacdonald Jan 17 '14 at 18:51

0 Answers0