0

我正在使用 Knockout.js。我有一个 HTML 表单,用户可以在其中向表格添加条目。下面是我的代码。

问题是您可以创建重复的条目。我不想允许那样。

我该如何补救?

HTML

<div class="span12">
  <button style="margin-bottom: 10px;" class="btn" data-bind="click: function () { ViewModel.AddIntMember() }"><i class="icon-plus"></i>Add</button>
</div>
        <div class="span8">

           <table class="table table-bordered table-condensed">
                <thead>
                    <tr>
                       <th></th>
                          <th>Name</th>                      
                                <th>Staff No</th>                       
                            </tr>
                </thead>
                <tbody data-bind="foreach: ViewModel.RiskAssessment.IntTeam">
                    <tr>
                        <td>
                            <button class="btn btn-small" data-bind="click: function () { ViewModel.StaffViewModel.Remove($data) }">
                                <i class="icon-remove"></i>
                                 Remove</button>
                         </td>
                                <td data-bind="text: Name"></td>
                                <td data-bind="text: StaffNo"></td>
                    </tr>
                </tbody>
            </table>
         </div>

JS 相关函数

AddIntMember: function () {
                    LoadStaff("", 0);
                    $("#InternalStaffPopup").bPopup({ positionStyle: "fixed", scrollBar: true });
                },


Select: function (staffMember) {
                        ViewModel.RiskAssessment.IntTeam.push({ Id: 0, RiskAssessmentId: 0, StaffNo: staffMember.StaffNo, Name: staffMember.Name });
                    },

Remove: function (staffMember) {
                        ViewModel.RiskAssessment.IntTeam.remove(staffMember);
                    },
4

1 回答 1

1

我将通过向您的视图模型添加两个可观察的属性来处理这个问题:名称和员工编号。像这样的东西

self.Name = ko.observable();
self.StaffNumber= ko.observable();

然后将输入元素添加到绑定到这些的 html 中。

<div class="span12">
<div>
<label for="StaffName">Street Address</label>
<input type="text" id="StaffName" data-bind="value: ViewModel.Name" />
</div>
<div>
<label for="StaffNumber">Street Address</label>
<input type="text" id="StaffNumber" data-bind="value: ViewModel.StaffNumber" />
</div>

<button style="margin-bottom: 10px;" class="btn" data-bind="click: function () { ViewModel.AddIntMember() }"><i class="icon-plus"></i>Add</button>
</div>

最后,在您的 AddIntMember 函数中,您只需在将它们添加到 ViewModel.RiskAssessment observableArray 之前检查重复项。

 AddIntMember: function () {
      //self.Name and self.StaffNumber contains the values the user entered
      //look through ViewModel.RiskAssessment.IntTeam for duplicates
      var isUnique = yourWayOfCheckingForDuplicates();
      if (isUnique) {
         LoadStaff("", 0);
         $("#InternalStaffPopup").bPopup({ positionStyle: "fixed", scrollBar: true });
      }
      else {
        //display to user that their entries need to be unique
      }},

玩得开心!

于 2013-02-07T17:39:02.863 回答