I am creating an Online Store App, made up of a few modules. The first module is the Data module, which provides the data for the rest of the app as well as a few useful methods. Here is the main gist of the module:
app.data = (function (pubsubService) {
//This is where the data is fetched
var items = app.UTILS.getAJAX('data.json', JSON.parse, false);
/* Items methods */
var getItems = function () {
return items;
};
var getItemsLength = function () {
return items.length;
};
function updateItemStock(item, amount) {
item.stock -= Number(amount);
}
return {
getItems: getItems,
getItemsLength: getItemsLength;
};
})(app.pubsub);
The items var is called via Ajax, with the following helper function:
function getAJAX(url, callback, async) {
async = async || true;
var xhr = new XMLHttpRequest();
xhr.open('get', url, async);
xhr.onload = function () {
callback(this.responseText);
};
xhr.send();
}
I've tried to make this call with Async on and off, and regardless of that, the result is an error, because later down the line there is another module which needs some information about the data, but the data loads only LATER, causing the error. The question is: How can I enforce the data to be loaded to items before moving on to initialisation of the next module?
*** EDIT **** This is an example of another module, which is dependent on Data:
app.mainView = (function (data, pubsubService) {
var items = [];
var generateItems = function (firstItemIndex, stopIndex) {
var dataLength = data.length;
stopIndex = (stopIndex < dataLength) ? stopIndex : dataLength;
items = data.slice(firstItemIndex, stopIndex);
pubsubService.publish('itemsGenerated');
};
var getItems = function () {
return items;
};
return {
generateItems: generateItems,
getItems: getItems
};
})(app.data.getItems(), app.pubsub);
Does this module really need to be defined inside the AJAX callback for this to work? I am not a fan of this solution