数据绑定json集合与knockoutjs

时间:2014-01-24 05:31:24

标签: jquery html json knockout.js

我是新手使用Knockoutjs,我遇到了一个问题,我很难过。我从服务器获取一个json对象,它是一个对象的集合,我试图使用knockoutjs将它绑定到一个列表。虽然有一些我想念的东西。我不确定如何引用被绑定的视图模型中的当前对象。

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);

}

......这是它所绑定的HTML:

<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>

JSON是一个可预测的对象集合,具有Id,Name,Date等,如果我不尝试使用视图模型将集合绑定到UI,则可以正常工作。我必须在这里错过一些简单的东西......

1 个答案:

答案 0 :(得分:1)

假设response是这样的:

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

您的视图模型看起来像这样:

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);
}