1

我的 json 调用返回一个对象数组:

[
{
Table: 1,
FirstName: "Bert",
LastName: "Smith",
Place: 1
},
{
Table: 1,
FirstName: "Suzanne",
LastName: "Smith",
Place: 2
},
{
Table: 1,
FirstName: "Matthew",
LastName: "Stewart",
Place: 3
},
{
Table: 1,
FirstName: "Brian",
LastName: "Robinson",
Place: 4
},
{
Table: 1,
FirstName: "Jennifer",
LastName: "Robinson",
Place: 5
},
{
Table: 1,
FirstName: "Andrew",
LastName: "Caygill",
Place: 6
},
{
Table: 1,
FirstName: "Susan",
LastName: "Caygill",
Place: 7
},
{
Table: 1,
FirstName: "John",
LastName: "Spreadbury",
Place: 8
},
{
Table: 1,
FirstName: "Anne-Marie",
LastName: "Nevin",
Place: 9
}]

我的 HTML 中有一个模板:

<script type="text/html" id="dataLine">
    <div class="itemLine">
        <div class="Name">
            <span class="fixtureBoxLine" data-bind="text: fullName"></span>
        </div>
        <div class="TableNo">
            <span class="fixtureBoxLine" data-bind="text: Table"></span>
        </div>
    </div>
</script>

绑定是:

<div data-bind="template: { name: 'dataLine', foreach: pageCol1 }"></div>

我的视图模型是:

var viewModel = {
    fields: ko.observableArray([]),
    pageSize: ko.observable(1),
    pageIndex: ko.observable(0)
}; 
viewModel.pageCol1 = ko.computed(function() {
    var size = Number(this.pageSize());
    var start = this.pageIndex() * size * 2; //2 cols per page
    var end = start + size;
    return this.fields.slice(start, end);
}, viewModel);

一切正常,除了我无法获得“全名”属性。如果我尝试以与上面使用“pageCol1”相同的方式将其添加到视图模型中,那么就像我的 json 成功属性一样:

viewModel.fields(xlData); 

它不起作用,因为返回的数据没有“fullName”属性。

我觉得我今天已经尝试了所有可能的组合,现在让自己头疼!请有人指出我正确的方向吗?

谢谢!

4

1 回答 1

0

尝试pageCol1通过将新字段(从另外两个连接)添加到响应数组来扩展您的响应数组,例如:

viewModel.pageCol1 = ko.computed(function() {
    var size = Number(this.pageSize());
    var start = this.pageIndex() * size * 2; //2 cols per page
    var end = start + size;

    for( var i = 0, len = this.fields.length; i < len; i++ ) {
        this.fields[ i ].fullName = this.fields[ i ].FirstName + ' ' + this.fields[ i ].LastName;
    }

    return this.fields.slice(start, end);
}, viewModel);

所以在你迭代你的数组之前的最终结果将是:

[
{
Table: 1,
FirstName: "Bert",
LastName: "Smith",
fullName: "Bert Smith",
Place: 1
},
{
Table: 1,
FirstName: "Suzanne",
LastName: "Smith",
fullName: "Suzanne Smith",
Place: 2
},
{
Table: 1,
FirstName: "Matthew",
LastName: "Stewart",
fullName: "Matthew Stewart",
Place: 3
},
...
于 2013-04-08T15:57:38.110 回答