0

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.

1 Answer 1

2

I would follow this paradigm for binding your vm to your sortable dom elements. Then you can just focus on ordering your observable array

Sign up to request clarification or add additional context in comments.

1 Comment

I knew this from before, but I didn't know that it was so easy to use as well. I had taken time to integrate this and works like a charm now in fact much better than I originally created sortable manually. Thanks !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.