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

Rus*_*hle 2 html jquery knockout.js knockout-sortable

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

使用knockout-sortable.js.例

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

JSFiddle示例

  [1]:http://jsfiddle.net/rniemeyer/hw9B2/
  [2]:https://jsfiddle.net/nagarajputhiyavan/x9vc10zu/3/
Run Code Online (Sandbox Code Playgroud)

Roy*_*y J 7

因为Knockout的整个想法是你使用你的数据模型并且Knockout让UI保持与它同步,所以基本问题只是重新排序你的数组(并且它需要是observableArrayKnockout注意到它的变化).

在你建议的两种方法中,向上和向下按钮更容易,所以这就是我的用法.我在每行添加了向上和向下按钮,第一行禁用了Up,最后一行禁用了Down.

向上按钮被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());
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

使用拖放会稍微复杂一些,因为重新排序发生在UI中,需要反映到数据模型中.您可以在自定义绑定处理程序中执行此操作,并且已编写此类处理程序.这是一篇关于它的文章.