2
votes

I have the following markup:

<table>
   <tr>
     <td style="padding-left: 150px;">
        <ul id="items" data-bind='foreach: Items'>
           <li>
              <span class="title" data-bind="text: $data.Title"></span>
            <li>  
      </td>
  </tr>
</table>

And the following javascript:

$(function () { 
  var ViewModel = function () {
        var self = this;
        self.Items= ko.observableArray();

        self.arrayChanged = function (array) {
            $.each(array, function (i, obj) {
                self.Items.push(obj);
            });
        };
    };
    var viewModel = new ViewModel();
    ko.applyBindings(viewModel, $("#items")[0]);
    viewModel.arrayChanged($.parseJSON('@Html.Raw(Json.Encode(Model.Items))'));               
});

The above is a much simplified version of what I'm trying to do. In the above

self.Items.push(obj);

doesn't work as it fails to push new items on the Items observableArray. I also tried using

ko.utils.arrayPushAll(self.Experiences, obj);

to no avail. Any ideas?

1
What does the JSON for Model.Items look like? - Andrew Whitaker
To be more specific - are you sure that this $.parseJSON('@Html.Raw(Json.Encode(Model.Items))') is array? - Ilya Luzyanin
in case of great emergency use self.Items.valueHasMutated() - john Smith
Yes, Ilya, $.parseJSON('@Html.Raw(Json.Encode(Model.Items))') produces an array. - UkraineTrain
John, I had tried using self.Items.valueHasMutated() before and it didn't help. - UkraineTrain

1 Answers

1
votes

Try using this

self.arrayChanged = function (array) {
    var arr = JSON.parse(array)    
    self.Items(arr)
};

convert json to object then pass array of objects to Items