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

2.1k Views Asked by At

I need to add text at the bottom of the document "The list was updated!" if the user updated the order of the sortable list.

Can you give me hints how to do it properly and in knockout-way?

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

2

There are 2 best solutions below

0
Jeff Mercado On BEST ANSWER

Add an afterMove handler to update your "was updated" flag. Then use that flag to display your message.

e.g.,

<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);
};
0
Jason Spake On

You can do this with a subscription to the observable array and a new observable to track the visible state of the notification.

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

Then add a notification with an if or visible binding below your tasks element.

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

Edit: Fiddle