【问题标题】:databinding json collection with knockoutjs带有knockoutjs的数据绑定json集合
【发布时间】: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


【解决方案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);
}

【讨论】:

  • 有趣。我不确定为什么要使用 self var,但是两个 javascript 函数都需要它吗?我注意到您的示例中有一个错误,应该是: list.push(new ListItemViewModel(response.List[i]));这是否意味着我需要将数据绑定语法更改为引用 ListItemViewModel 对象的内容,因为不再有包含列表的列表?
  • 不,在这些视图模型中,您可以使用this 而不是selfself 的定义是,当您在视图模型中的函数中时,您仍然可以访问视图模型(因为 this 根据上下文指向不同的对象)。
  • 你说得对,我的代码不正确;我更新了我的答案。数据绑定语法应该与现在一样正确,因为您正在循环List。这意味着您可以在 foreach 中使用 ListItemViewModel 的所有属性。
  • 那么最后一个问题。我一直在尝试您提供的示例代码,但它没有显示任何内容。我怀疑需要在某处调用 ko.applyBindings() 来应用所有内容。对吗?
  • 是的,如果没有ko.applyBindings(new ListViewModel(response)); 调用,它不会做任何事情
猜你喜欢
  • 1970-01-01
  • 2011-11-16
  • 1970-01-01
  • 1970-01-01
  • 2013-08-09
  • 2012-02-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多