Please excuse the awkward title I'll try my best to explain my peculiar problem.
I have three bits of javascript code:
- Some self executing code which calls my personal Ajax function and passes it a callback.
- The ajax function itself which retrieves the data calls the callback passing it the data.
- The callback itself which takes in the data and parses it into an array of n length.
What should be noted is that the self executing code and the callback function are defined within their own closure. The ajax function is accessed through an imported named closure which I defined as $.
I am fairly new to JavaScript and I am still learning about closures and their scopes. I have reason to believe that this problem is probably related to that.
Anyway, my problem relates to trying to access that supposedly populated array. Since I defined the array in a suitable scope (or so I believe) as the parse function I think I should have no problem pushing items into it.
This is self exectuting :
(function ($){
//Load stock
var items = [];
var response = $.Ajax("scripts/Lookup.php","GET",parse);
function parse(a){
for(/*Simplified view*/){
var item = new $.Item();
item.name = domStuff.textContent;
item.description = domStuff.textContent;
item.price = domStuff.textContent;
item.id = domStuff.textContent;
items.push(item);
}
}
//Test the length (and verify contents)
for(var i=0; i < items.length; i++){
alert(items[i].price);
}
}($));
This is my definitions, which includes the Ajax function:
var $ = (function(){
var s = {};
var ajax = function(url,method,callback){
var a = new XMLHttpRequest();
a.open(method, url, true);
a.onreadystatechange = function(){
if(this.readyState==4){
callback(a);
}
}
a.send();
};
s.Ajax = (function(){
return ajax;
}());
return s;
}());
So what justifies the title is that when I probe the code with firebug, I can see that items is populated with 3 Objects correctly defined by the parsed data.
The loop then alerts as intended 3 times.
However, if I remove the break points and have firebug ignore the code then the loop doesn't play out and I can only assume that the array is empty.
The code works also if I alert(items) prior to the test loop.