This is my first firefox extension, and I'm trying to collect some
information from several sites and mash'em up into one page. But I
need to do processing specific to each asynchronous request. All the
examples I've found use a global httpRequest object that is processed
by a callback function. But I can never know what request is actually
in the httpRequest at a given time. So I tried to make an array of
such requests. But I can't seem to get around the global problem
because I can't seem to tell the processing functions what they should
process.
I thought this would work, but apparently because of closures or
something, the i variable is global with respect to the anonymous
function:
//----------------- start code -----------------------
var httpRequest = Array();
// urls is an array of URLs
// searchData is an array the same size as URLs containing data to be
searched on the corresponding URL
for (var i=0; i< urls.length; i++) {
httpRequest[i] = false;
httpRequest[i] = new XMLHttpRequest();
httpRequest[i].onreadystatechange = function() {
var id = i;
alert("der "+ id + " " + httpRequest[id]);
if (httpRequest[id].readyState == 4) {
if (httpRequest[id].status == 200) {
var processedData = getData(httpRequest[id].responseText,
searchData[id]);
}
}
};
httpRequest[i].open('GET', URL, true);
httpRequest[i].send(null);
}
//------------------ end code -----------------------
Any ideas on how I can make my callback function (anonymous here, but
didn't work the normal way either) know which httpRequest it is
answering?
Martin Honnen - 28 Feb 2007 12:54 GMT
> var httpRequest = Array();
> // urls is an array of URLs
[quoted text clipped - 14 lines]
> }
> };
httpRequest[i].onreadystatechange = function (index) {
return function () {
if (httpRequest[index].readyState == 4) {
// continue to use use httpRequest[index] here
...
}
};
}(i);

Signature
Martin Honnen
http://JavaScript.FAQTs.com/
jeff.maildump@gmail.com - 28 Feb 2007 14:34 GMT
> jeff.maild...@gmail.com wrote:
> > var httpRequest = Array();
[quoted text clipped - 29 lines]
> Martin Honnen
> http://JavaScript.FAQTs.com/
Hi, thanks for the quick reply. Where is index initially set? When
does the first function get passed this index?
Martin Honnen - 28 Feb 2007 14:44 GMT
>> httpRequest[i].onreadystatechange = function (index) {
>> return function () {
[quoted text clipped - 4 lines]
>> };
>> }(i);
^^^
^^^
> Where is index initially set? When
> does the first function get passed this index?
The loop variable i is passed in as the argument to the anonymous function.

Signature
Martin Honnen
http://JavaScript.FAQTs.com/
jeff.maildump@gmail.com - 28 Feb 2007 14:51 GMT
> jeff.maild...@gmail.com wrote:
> >> httpRequest[i].onreadystatechange = function (index) {
[quoted text clipped - 18 lines]
> Martin Honnen
> http://JavaScript.FAQTs.com/
Oh yes, I overlooked the i at the very end. I'll try that when I get
home tonight. Thanks a lot!.