enkdr
enkdr

Reputation: 363

updating html with new data Knockout.js

I am retreiving new data using getJson

    function getDaysMeals(dayid)
    {           
        $.getJSON('jsonchoose/'+ dayid +'', function(data) {
                var viewModel = {
                    dayMeals: ko.observableArray(data)
                };
                ko.applyBindings(viewModel);
            });

    }

I have click event to fire $.getJson with a 'dayid' to get new data.

I am trying to update table with the new data - at the moment it is adding to the existing data each time.

  <table>
<tbody data-bind="foreach: dayMeals">
  <tr>
    <td data-bind="text: description" class="display-meal"></td>
    <td data-bind="text: measure" class="display-meal"></td>
    <td data-bind="text: total_cal" class="display-meal"></td>
  </tr>
</tbody>

Upvotes: 0

Views: 2291

Answers (1)

Sandeep G B
Sandeep G B

Reputation: 4015

In the code applybindings is getting invoked every time you call getJSON().

You should call applybindings only once. Probably you can move applyBindings() to a place of initialization or conditionally invoke it only once.

//Make necessary changes as per your requirement.
var viewModel;

function onLoad()
{
 viewModel = { dayMeals: ko.observableArray([]) };
 ko.applyBindings(viewModel);
}

function getDaysMeals(dayid)
{           
  $.getJSON('jsonchoose/'+ dayid +'', function(data) {
  // This is just for reference. Minor change may be required.
   viewModel.dayMeals(data); 
   });
}

Upvotes: 5

Related Questions