Roger Hill
Roger Hill

Reputation: 4109

databinding json collection with knockoutjs

I'm new to using Knockoutjs, and I have been having a problem that I am stumped on. I am getting a json object from the server that is a collection of objects, and I am trying to use knockoutjs to bind it to a list. There is something I am missing though. I am not sure how to refer to the current object in the view model that is being bound.

function GetGameListResponse(response)
{
    if (response.Error == null)
    {
        // this is my test, when I bind the collection directly everything works fine...
        //ko.applyBindings(response, document.getElementById('panGames'));

        // this doesn't work
        ko.applyBindings(new ListViewModel(response), document.getElementById('panGames'));
    }
}
function ListViewModel(response)
{
    var self            = this;

    // this is where the problem is I think, as 'response'
    self.Id             = ko.observable(response.Id);
    self.Name           = ko.observable(response.Name);
    self.Date           = ko.observable(response.Date);
    self.Description    = ko.observable(response.Description);

}

...And here is the html it binds to:

<table>
<thead>
<tr>
    <th>Name</th>
    <th>Date</th>
    <th>Description</th>
    <th>select</th>
</tr>
</thead>
<tbody data-bind="foreach: List">
<tr>
    <td data-bind="text: Name"></td>
    <td data-bind="text: Date"></td>
    <td data-bind="text: Description"></td>
    <td></td>
</tr>
</tbody>
</table>

The JSON is a predictable collection of objects with Id,Name,Date,etc that works fine if I don't try to use a view model to bind the collection to the UI. I must be missing something simple here...

Upvotes: 1

Views: 139

Answers (1)

sroes
sroes

Reputation: 15053

Well assuming response is something like this:

{
    List: [
        {
            Name: "Name",
            Date: "Date",
            Description: "Description"
        }
    ]
}

Your view models would look something like this:

function ListViewModel(response)
{
    var self            = this;

    var list = [];
    for (var i = 0; i < response.List.length; i++) {
        list.push(new ListItemViewModel(response.List[i]));
    }
    self.List = ko.observableArray(list);
}

function ListItemViewModel(data)
{
    var self            = this;

    self.Id             = ko.observable(data.Id);
    self.Name           = ko.observable(data.Name);
    self.Date           = ko.observable(data.Date);
    self.Description    = ko.observable(data.Description);
}

Upvotes: 1

Related Questions