LockTar
LockTar

Reputation: 5467

How to set the order property after sorting with knockout

I have a knockout object (menu) and I want to sort that menu with drag and drop. I found jQuery Sortable that is a nice plugin so you could sort a list in your dom. But how do I bind that order against the knockout object order property? I can't use the $index property of knockout because the array isn't adjusted.

I've created a fiddle so you could see an example. It must be possible that the menu is nested like in this fiddle.

Fiddle

<ol data-bind="foreach: people" class='example'>
<li>
    Knockout position <span data-bind="text: $index"> </span><br />
    Item name: <span data-bind="text: name"> </span><br />
    Order that I want to save in database: <span data-bind="text: order"> </span>

    <ol></ol>
</li>

function AppViewModel() {
var self = this;

self.people = ko.observableArray([
    { name: 'Item A', order: 1 },
    { name: 'Item B', order: 2 },
    { name: 'Item C', order: 3 }
]);
}

ko.applyBindings(new AppViewModel());

$(function  () {
$("ol.example").sortable({
    onDrop: function ($item, container, _super) {
        $item.removeClass("dragged").removeAttr("style");
        $("body").removeClass("dragging");

        // Set the order property of the person right in the ui here????            
    }
});
})


body.dragging, body.dragging * {
  cursor: move !important;
}

.dragged {
  position: absolute;
  opacity: 0.5;
  z-index: 2000;
}

ol.example li.placeholder {
   position: relative;
   /** More li styles **/
}
ol.example li.placeholder:before {
   position: absolute;
   /** Define arrowhead **/
}

Upvotes: 0

Views: 720

Answers (1)

RP Niemeyer
RP Niemeyer

Reputation: 114792

The knockout-sortable library handles keeping a sortable section in sync with an observableArray. You can also have nested sortable lists.

If you do not want to be able to drop items from one level into another, then you can use the connectClass option to restrict which other sortables can participate with it.

Upvotes: 0

Related Questions