Im trying to implement a vanilla javascript app that reads a JSON from a local server and with that JSON content I need to populate a select. The problem I have is that I´m trying to separate the code in 3 modules and my idea is to call the XMLHttprequest on the Model and set the json to a private Model variable(appData.categories). And then use the data from the Model variable on the View to display it on a select.
var Model = (function () {
var appData = {
categories: []
}
function initCategories() {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open("GET", "/services/categories/", true);
xobj.onload = function () {
if (xobj.readyState == 4 && xobj.status == "200") {
appData.categories = JSON.parse(xobj.responseText);
}
};
xobj.send(null);
}
function getCategories() {
return appData.categories;
}
return {
initCategories: initCategories,
getCategories: getCategories
}
})();
View
var View = (function () {
function displayData(total) {
console.log(total);
}
return {
displayData: displayData
}
})();
Controller
var Controller = (function (modelCtrl, uiCtrl) {
function initCategories() {
modelCtrl.initCategories(); // Call to async method
var data = modelCtrl.getData(); // tries to get data
uiCtrl.displayData(data); // data is an empty array at this point
}
function init() {
initCategories();
console.log("app started");
}
return {
init: init
}
})(ModelController, UIController);
Call to init function
Controller.init();
When i call the getCategories() method the variable is not populated yet, I can fill the select from inside the model the first time but I think there must be a better way. Thanks!