EchO
EchO

Reputation: 1344

ViewModel not updating when calling a function update()

I have this function:

function updatedata(data)
{
  var obj = jQuery.parseJSON(data);

  if(obj.hasOwnProperty('request_type'))
  {
     if (obj.request_type == 'client_information')
     {

         var ViewModel = function (Clients) {
             var self = this;
             this.Clients = ko.mapping.fromJSON(JSON.stringify(Clients));
         };

         var info = new ViewModel(obj.clients_information);
         ko.applyBindings(info);
     }
  }
}

HTML:

<ul id="mychats" data-bind="foreach: Clients" data-role="listview"> 
<li class="not_selected" data-bind="id: chatid, text: client_name"></li> 
</ul> 

The function is called time to time , it can correctly bind the data to the ul when it's called for the first time but not when its being called more than one time.

Upvotes: 0

Views: 58

Answers (1)

xlecoustillier
xlecoustillier

Reputation: 16351

You shouldn't apply the bindings more than once (which should raise an error - check your console).

Instead of recreating the viewModel each time, just put the clients information in an observable and update the observable with the new client info in the update function.

Something like:

 var ViewModel = function (Clients) {
     var self = this;
     this.Clients = ko.observableArray(Clients); // As you use the foreach binding, I assume it's an array
 };

 var obj = jQuery.parseJSON(data);

 var info = new ViewModel(obj.clients_information);
 ko.applyBindings(info);

function updatedata(newData)
{
    info.Clients(newData);
}

See this fiddle.

Or if you want to use ko.mapping:

var viewModel = ko.mapping.fromJS(obj);

function updatedata(newData)
{
    ko.mapping.fromJS(newData, viewModel);
}

This injects the new data into the existing viewModel.

As an aside, there is no id binding. Use attr: { id: chatid } instead.

Upvotes: 3

Related Questions