如何使用knock out更改表的行顺序。拖放或使用向上/向下按钮

时间:2016-03-22 07:57:26

标签: jquery html knockout.js knockout-sortable

如何使用knockout更改表的行顺序。我有小提琴:

使用knockout-sortable.js。实施例

请协助。 我的小提琴如下:

JSFiddle示例

  [1]:http://jsfiddle.net/rniemeyer/hw9B2/
  [2]:https://jsfiddle.net/nagarajputhiyavan/x9vc10zu/3/

1 个答案:

答案 0 :(得分:6)

由于Knockout的整个想法是你使用你的数据模型并且Knockout让UI保持与它同步,所以基本问题只是重新排序你的数组(并且它需要是一个observableArray来敲除注意它的变化)。

在您建议的两种方法中,“向上”和“向下”按钮更容易,这就是我使用的方法。我为每一行添加了向上和向下按钮,第一行禁用了Up,最后一行禁用了。

向上按钮是click - 绑定到moveUp函数,该函数拼接当前行并将其拼接回来。 Down做了同样的事情,但连续拼接下来。



var AppModel = function() {
  var self = this;
  
  this.itemsToReceive = ko.observableArray([{
    RecordId: 1,
    IsPriority: true,
    IsInTransit: true,
    IsSpecialRecall: true
  }, {
    RecordId: 2,
    IsPriority: false,
    IsInTransit: true,
    IsSpecialRecall: true
  }, {
    RecordId: 3,
    IsPriority: false,
    IsInTransit: true,
    IsSpecialRecall: true
  }]);
  
  this.moveUp = function(data) {
    var idx = self.itemsToReceive.indexOf(data),
      tmp = self.itemsToReceive.splice(idx, 1);

    self.itemsToReceive.splice(idx - 1, 0, tmp[0]);
  };
  
  this.moveDown = function(data) {
    var idx = self.itemsToReceive.indexOf(data),
      tmp = self.itemsToReceive.splice(idx, 1);

    self.itemsToReceive.splice(idx + 1, 0, tmp[0]);
  };
  
  this.loadGridServerSide = function() {
    self.itemsToReceive([{
      RecordId: 1,
      IsPriority: true,
      IsInTransit: true,
      IsSpecialRecall: true
    }]);
  }
}

ko.applyBindings(new AppModel());

<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<button data-bind="click: loadGridServerSide" class="btn btn-primary">Server Side Invoke</button>
<table class="table static-table table-bordered table-hover no-bottom-margin">
  <thead>
    <tr>
      <th>Item Number</th>
      <th>Priority?</th>
      <th>Transit?</th>
      <th>SpecialRecall?</th>
    </tr>
  </thead>
  <tbody data-bind="foreach: itemsToReceive">
    <tr>
      <td data-bind="text: RecordId"></td>
      <td>
        <input type="checkbox" data-bind="checked: IsPriority" />
      </td>
      <td>
        <input type="checkbox" data-bind="checked: IsInTransit" />
      </td>
      <td>
        <input type="checkbox" data-bind="checked: IsSpecialRecall" />
      </td>
      <td>
        <button data-bind="disable: $index() === 0, click: $parent.moveUp">Up</button>
        <button data-bind="disable: $index() === $parent.itemsToReceive().length - 1, click: $parent.moveDown">Down</button>
      </td>
    </tr>
  </tbody>
</table>
&#13;
&#13;
&#13;

使用拖放会稍微复杂一些,因为重新排序发生在UI中,需要反映到数据模型中。您可以在自定义绑定处理程序和such a handler has been written中执行此操作。这是an article about it