-1

I'm having problems with the following bit of code (I've omitted irrelevant lines):

var audios = function(url){
    this.loaded = false;
    req.onload = function () {
        this.loaded = true;
    }
}

The object member this.loaded is not being updated to true when the XHR loads. And it definitely gets to the onload function. I think I'm not referencing it correctly, but I can't work out how. Any help would be great, thanks.

tshepang
  • 12,111
  • 21
  • 91
  • 136
  • 1
    are you trying to access it before the callback executes? – John Dvorak Oct 02 '13 at 16:07
  • possible duplicate of [How to return the response from an AJAX call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call) – John Dvorak Oct 02 '13 at 16:09
  • I create an instance of 'audios' in the global scope and repeatedly check it's loaded state until it is true. – mattomatto Oct 02 '13 at 16:13
  • that's a bad way to do it, but do you at least wait a little before each check? If not, the callback won't get a chance to run. – John Dvorak Oct 02 '13 at 16:15
  • I use a setInterval to periodically check every 500ms... This is part of a preloader that uses XHRs to load files. I've not found any other way to do it... – mattomatto Oct 02 '13 at 17:10

1 Answers1

1

In your code the second this refers to req. Try this instead :

var audios = function(url){
    var me = this;
    this.loaded = false;
    req.onload = function () {
        me.loaded = true;
    }
}