foreach只迭代我的数组的最后一个条目

时间:2015-05-23 00:40:30

标签: javascript knockout.js

我正在尝试使用knockout foreach绑定加载我的表,它可以读取我的数组中有多少项,但循环数据只是我的数组中的最后一个条目。

要想象我的问题,而不是(仅限样本):

<td> 1st </td>
<td> 2nd </td>
<td> 3rd </td>

输出:

<td> 3rd </td>
<td> 3rd </td>
<td> 3rd </td>

这是我的观点:

<table id="clientsTable" class="table table-bordered">
    <thead>
        <tr>
            <th style="width: 10px; text-align:center">#</th>
            <th>Full Name</th>
            <th>Location</th>
            <th>Address</th>
            <th>Member Date</th>
            <th>Mobile No</th>
            <th>Alternate Mobile No</th>
            <th style="width: 70px">Actions</th>
        </tr>
    </thead>
    <tbody data-bind="foreach: clientsList">
        <tr>
            <td> <strong data-bind='text: clientID'></strong></td>
            <td> <span data-bind="text: fullName"> </span></td>
            <td> <span data-bind="text: locationID"> </span></td>
            <td> <span data-bind="text: address"> </span></td>
            <td> <span data-bind="text: memberDate"> </span></td>
            <td> <span data-bind="text: mobileNo"> </span></td>
            <td> <span data-bind="text: mobileNoAlternate"> </span></td>
        </tr>
    </tbody>
</table>

这是脚本部分:

var clientLine = function (cid, lid, fname, lname, mname, fullname, fullname2, memdate, address, mobileno, mobilenoalt, cpid) {
    self.clientID = ko.observable(cid),
    self.locationID = ko.observable(lid),
    self.firstName = ko.observable(fname),
    self.lastName = ko.observable(lname),
    self.middleName = ko.observable(mname),
    self.fullName = ko.observable(fullname),
    self.fullName2 = ko.observable(fullname2),
    self.memberDate = ko.observable(memdate),
    self.address = ko.observable(address),
    self.mobileNo = ko.observable(mobileno),
    self.mobileNoAlternate = ko.observable(mobilenoalt)
};

function Clients(data) {
    var self = this;
    self.clientsList = ko.observableArray(ko.utils.arrayMap(data, function (client) {
        return new clientLine(client.ClientID, client.LocationID, client.FirstName, client.LastName, client.MiddleName, client.FullName, client.FullName2, client.MemberDate, client.Address, client.MobileNo, client.MobileNoAlternate)
    }));
};

var viewModel = new Clients(@Html.Raw(JsonConvert.SerializeObject(Model)));
$(document).ready(function () {
    ko.applyBindings(viewModel);
});

我的视图接收并转换我的模型,我可以看到它正确地将我的模型转换为json数组。如果有人能指出我的问题的原因,这将真正帮助我,并非常感激。

1 个答案:

答案 0 :(得分:3)

您未在self中声明clientLine,因此它将进入全球范围。

无论

  • self
  • 中声明clientLine
  • 使用this代替。