The problem "the key is always the last one in the array" is indeed happening because the 'load' events only get fired after the loop is over, so
key
is indeed equal to the last key at the time you call
alert(key)
. This problem can be solved by replacing your
addEventListener
call by this:
xhr.addEventListener('load', (function(k) {
return function() {
alert(k);
myobj[k]._c = this.responseText;
};
})(key));
This looks a bit complicated, so let's break this piece of code down into its different parts.
(function(k) { ... })(key)
The above is a self-executing function. When the function executes itself, we pass
key
as the
k
parameter:
k
will be the key at the time that
addEventListener
got called and
it will not be affected by changes to the key
variable.
Inside the self-executing function, we return a new function. We need to do that because we do not want to run
alert
(and the other line) immediately: we want to have a function that we can pass to
addEventListener
so that it runs on the 'load' event. So we have to return the function that we want to get fired on the 'load' event:
return function() {
alert(k);
myobj[k]._c = this.responseText;
};
We use
k
here and not
key
, because we want to use the variable inside the self-executing function that doesn't get affected by
key
changes.