0

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!

Keff6
  • 9
  • 3
  • 1
    you seem to understand that `modelCtrl.initCategories` populates `appData.categories` asynchronously - do you know what that means though? – Jaromanda X Jul 26 '17 at 01:00
  • I'm actually learning a lot of topics about it and still in the process of understand it, but with that structure I'm using, would you suggest me to populate the select on the initCategories itself? Because I can do that but I feel that I'm doing a bad use of MVC then. I want to do it without transgreding MVC principles. Thanks for your response! – Keff6 Jul 26 '17 at 02:51

0 Answers0