Search code examples
knockout.jsknockout-3.0knockout-sortable

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


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


Solution

  • 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);
    };