I'm creating a page with multiple "widgets", each with its own
XMLHttpRequest object, so the user can play with the widgets in
parallel. The widgets are enclosed in divs with class "widget" and a
unique ID which tells me the name of the PHP file for the widget.
Each widget should be able to access its PHP file with GET and POST
methods, and to re-draw its innerHTML on response.
I am using a simple Ajax library called XHConn (http://xkr.us/code/
javascript/XHConn/) by Brad Fults. Making the requests from within
each widget doesn't seem too hard, but the response handling is a
little difficult. Each response handler function should write output
to the correct widget. But if I create all these response handler
functions with a loop, they all use the latest "i" on execution. See:
widgetArray = getElementsByClassName("widget");
for (var i=0; i<widgetArray.length; i++) {
widgetConn[widgetArray[i].id] = new XHConn();
widgetReloaders[widgetArray[i].id] = function (oXML)
{ widgetArray[i].innerHTML=oXML.responseText };
As you see I dynamically create three arrays, one for the divs, one
for the XMLHttpRequest objects, and one for the response handlers.
The problem is the "widgetArray[i]" in the response handler. I want
it to use the "i" at the time I created the function, not the "i" at
the time of execution (which is always one past the end of the
array). Can I do this? Is there a better way?