Question

I have a json structure that looks like the following, where "Position" is a sort value.

 [
  {"ID":1, "Title":"Title 1", "Position":1},
  {"ID":2, "Title":"Title 2", "Position":2},
  {"ID":5, "Title":"Title 3", "Position":3},
  {"ID":7, "Title":"Title 4", "Position":99}
];

knockout-sortable uses an index to sort sortable items

Is there a way to bind this sortable index value to my Position property?

Here is a jsFiddle of my code.

Basically, when an item is dragged to a new position, I want to update the viewmodule so that I can save the change back to the database.

Was it helpful?

Solution

For something like this, I like to add a subscription to my observableArray that takes one pass through the array and properly sets the "index".

Here is an extension that would work for your use case:

ko.observableArray.fn.withIndex = function(prop, startIndex, lastIndex) {
    //by default use an "index" observable
    prop = prop || "index";

    //whenever the array changes, make a single pass through to update the indexes
    this.subscribe(function(newValue) {
        var item;
        for (var i = 0, j = newValue.length; i < j; i++) {
            //create the observable if it does not exist
            item = newValue[i];

            if (!item[prop]) {
                item[prop] = ko.observable();
            }

            //special logic for the last one 
            item[prop]((lastIndex && i === (j - 1)) ? lastIndex : startIndex + i);   

        }
    }, this);

    return this;
};

You would use it like:

myObservableArray.withIndex("Position", 1, 99);

Here is your updated sample: http://jsfiddle.net/rniemeyer/HVNUr/

OTHER TIPS

I added an id on list container so I can "listen" dom modification that alter it. I wrap the update position process in timer because the dom modification event was fired too much times.

var positions = ko.utils.arrayMap(viewModel.Items(), function (item) {
    return item.Position();
});
positions.sort();
var itmer = null;

$('#container').bind('DOMNodeInserted DOMNodeRemoved', function () {
    if (itmer) clearTimeout(itmer);

    itmer = setTimeout(function () {
        var items = viewModel.Items();
        ko.utils.arrayForEach(items, function (item) {
            var index = $('#container [id=' + item.ID() + ']').last().index();
            var newPosition = positions[index];
            item.Position(newPosition);
        });
    }, 50);

});

See fiddle

I hope it helps.

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