【发布时间】:2014-02-15 00:04:33
【问题描述】:
我是使用 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,它可以正常工作。我一定在这里遗漏了一些简单的东西......
【问题讨论】:
-
你能发布一个示例 JSON 吗?
-
{ 列表:[{ 名称:“FirstThing”,日期:“1/22/13”,描述:“Fooo”},{ 名称:“SecondThing”,日期:“1/23/ 13", 描述: "Fooo" }]}
标签: jquery html json knockout.js