Question

I'm kind of new to knockout, but with the help of Google and stack overflow I've managed to find the pieces I need. I just cant seem to get them to work together.

So I've taken pieces of RP Niemeyer's code posted as answers here or on his site. I'm using knockout sortable, dirty flag and observing index of sortable items.

What I'm looking for is a way to make the sortable update its order when I revert the dirty items. The indexed property on my objects get reverted, but the order of the items in the sortable area is not updated based on the reverted values.

Here's a fiddle with an example of the problem.

If you move "Item 1" to after "Item 2" you'll see that both items become dirty (as they should). Then click the "Revert" button. Notice how the items "Order" gets updated, but not their order in the sortable.

To make it worse (it's kinda a side effect of the problem), move "Item 3" to after "Item 4" and you'll see that now item 1 through 4 are marked as dirty.

This is because of the order of the sortable items not being reset when you revert the dirty items. "Item 1" has the value 0 for its order observable, but it's in index 1 in the sortable. Hence the code marks it as dirty again.

I would very much appreciate if someone could point out what I need to change in order to make it work like I want.

The code is quite lengthy and I wouldn't know which part to post here, but apparently I need a code block to be allowed to post my fiddle link. :(

Thanks in advance, Ludvig

Was it helpful?

Solution

with your current structure, I think that you could add a few lines to your view model level revertItem function to put the items back in the "correct" order. Something like:

    self.revertItem = function (preset) {
        $.each(preset.dirtyItems(), function (index, item) {
            item.revert();
        });

        //new code added to sort based on order
        self.items.sort(function(a, b) {
            return a.order() > b.order() ? 1 : -1; 
        });
    };     

Updated fiddle: http://jsfiddle.net/rniemeyer/d2e5c/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top