Knockout Sortable - 如何知道可排序列表已更新

Knockout Sortable - How to know that the sortable list was updated

如果用户更新了可排序列表的顺序,我需要在文档底部添加文本"The list was updated!"。

你能告诉我如何正确地以淘汰赛的方式做到这一点吗?

var Task = function(name) {
  this.name = ko.observable(name);
}

var ViewModel = function() {
  var self = this;
  self.tasks = ko.observableArray([
    new Task("Get dog food"),
    new Task("Fix car"),
    new Task("Fix fence"),
    new Task("Walk dog"),
    new Task("Read book")
  ]);
};

ko.applyBindings(new ViewModel());
div {
  padding: 5px;
  margin: 5px;
  border: black 1px solid;
}

ul {
  padding-bottom: 10px;
}

.container {
  float: left;
  width: 150px;
  background-color: #ffd;
}

.item {
  background-color: #DDD;
  cursor: move;
  text-align: center;
}

#results {
  float: left;
  width: 150px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.min.js"></script>

<script src="https://rawgit.com/rniemeyer/knockout-sortable/master/build/knockout-sortable.js"></script>

<script src="https://rawgit.com/rniemeyer/knockout-sortable/master/build/knockout-sortable.js"></script>




<div class="container" data-bind="sortable: tasks">
  <div class="item">
    <a href="#" data-bind="text: name"></a>
  </div>
</div>


<div id="results">
  <ul data-bind="foreach: tasks">
    <li data-bind="text: name"></li>
  </ul>
</div>

JSfiddle link

您可以通过订阅 observable 数组和一个新的 observable 来跟踪通知的可见状态。

self.isUpdated = ko.observable(false);
self.tasks.subscribe(function(value){
    self.isUpdated(true);
});

然后在任务元素下方添加带有 if 或可见绑定的通知。

<span style="color: red" data-bind="if: isUpdated">The list was updated!</span>

编辑:Fiddle

添加一个 afterMove 处理程序来更新您的 "was updated" 标志。然后使用该标志显示您的消息。

例如,

<div class="container" data-bind="sortable: { data: tasks,
                                              afterMove: setIsUpdated.bind($root) }">
var ViewModel = function() {
  this.tasks = ko.observableArray([
    new Task("Get dog food"),
    new Task("Fix car"),
    new Task("Fix fence"),
    new Task("Walk dog"),
    new Task("Read book")
  ]);
  this.isUpdated = ko.observable(false);
};
ViewModel.prototype.setIsUpdated = function () {
  this.isUpdated(true);
};