Search code examples
javascriptjqueryajaxknockout.jsko.observablearray

knockout updating the property of observable array's each element using data from an ajax call


I have a ViewModel "AppViewModel" which is getting a JSON data to create the model from, one of the property "totalSessions" is to be fetched using an ajax call, the "model" AppViewModel returns an observable array, My code is running without any errors but the view doesn't seem to update.

    var jsonapparray = [];

   function AppViewModel(appsdata)
{
    var self = this;        
    var appsdata = $.parseJSON("["+ JSON.stringify(appsdata["user_of"]) + "]");

    var totalSessions = 0;
    var i = 0;               
    for (var appkey in appsdata[0]) {
      console.log(appsdata[0][appkey].name);
      var elem = new Object();
      elem._id = appsdata[0][appkey]._id;
      elem.category = appsdata[0][appkey].category;
      elem.country = appsdata[0][appkey].country;
      elem.name = appsdata[0][appkey].name;
      elem.key = appsdata[0][appkey].key;
      elem.timezone = appsdata[0][appkey].timezone;
      elem.totalsessions = 000;   
      jsonapparray.push(elem);
      updateSessionsInfo(i,elem,jsonapparray);
      i++;    
    }

    self.AppCount = i;
    self.Apps = ko.observableArray(jsonapparray);   

    function updateSessionsInfo(i,elem,jsonapparray)
    {          
        $.ajax({
                type:"GET",
                url:Domain + "/o",
                data:{
                    "api_key":readCookie("api_key"),
                    "app_id":elem._id,
                    "method":"sessions"
                },
                dataType:"jsonp",
                async: false,
                success:function (json) {                   
                    _sessionDb = json;
                    var totalSessions = _.pluck(_sessionDb,"t");                                    
                    jsonapparray[j].totalsessions = totalSessions[0];
                }
            });     
    }   

}

Solution

  • You should change:

    jsonapparray[j].totalsessions = totalSessions[0];
    

    to:

    jsonapparray[i].totalsessions = totalSessions[0];
    

    But that won't actually help. Updating a property of an item in the array won't trigger an update. You should make all your properties observable, for example:

    elem.totalsessions = ko.observable(0);
    

    and then update the value like this:

    jsonapparray[i].totalsessions(totalsessions[0]);