Scenario: Sorting elements in knockout/jquery sortable ui
I use the following event when item is received in the sortable:
beforeStop: function (event2, ui2) {
draggedItem2 = ui2.item;
itemDroppedIndex2 = ui2.item.index();
if (fieldInSortable) {
// change order of the item
var startPos = $(this).data('start_position');
// Update order
ko.contextFor(this).$data.updateElementPriorities(startPos, itemDroppedIndex2);
} else {
fieldInSortable = false;
}
},
The updateElementPriorities is as follows:
self.updateElementPriorities = function (oldIndex, newIndex) {
var fieldUpdated = null;
for (var j = 0; j < self.elementTypes().length; j++) {
var eType = self.elementTypes()[j];
var currPriority = eType.priority();
if (currPriority == oldIndex && !fieldUpdated) {
eType.priority(newIndex);
fieldUpdated = eType;
}
else if (newIndex < oldIndex) {
if (currPriority >= newIndex)
eType.priority(currPriority + 1);
}
else if (newIndex > oldIndex) {
if (currPriority <= newIndex)
eType.priority(currPriority - 1);
}
}
};
I use following code to get the sorted items based on priority():
var sorted = elementTypes.sort(function (l, r) {
return l.priority() > r.priority() ? 1 : -1;
});
return sorted;
Problem:
When adding new elements or when sorting the current elements, usually they dont get sorted the way it should be. Sometimes, I mean sometimes, it shows the correct priority() number but the order is not correct in UI. Is there any other algo; more efficient to do this sorting manually and display the get the correct sorted elements?
I am in a stage where I can not use any libraries or make major changes which would be a risk to do so. So I would like any suggestion/change in the same code structure please
Update: Some of the priority() properties start getting negative values when I do a lot of dragging around, not yet added any new item. Just by sorting existing items in the page.