I am currently trying to develop a small function using knockout-sortable which should work as follows.
I have 3 observable collections: The first is an empty droppable area, the 2nd contains the 1st 3 items from a collection(visible) and the 3rd contains the remainder of my dataset(hidden). When dragging an item from the 2nd collection onto the 1st, the 1st item in the 3rd array that matches the "group" property of the item that has just moved needs to be inserted into the 2nd observable at the same index as the item that was just dragged out. It all seems to work, except when adding an item from the 3rd to second array at the 1st index it always ends up at the back of array. I have even added an if statement which will use unshift to combat this but it doesn't seem to work. Any help would be much appreciated. Here is a snippet of code where I attempt to insert the object into the correct index.
self.GetNextItemForClass = function(group, sourceIndex) {
var nextItem = ko.utils.arrayFirst(self.lowPriorityTasks(), function(item) {
if (item == null)
return null;
return item.group() === group;
});
if (nextItem != null) {
var items = self.lowPriorityTasks();
if (sourceIndex == 0) {
self.normalPriorityTasks.unshift(nextItem);
} else {
self.normalPriorityTasks.splice(sourceIndex, 1, nextItem, items[sourceIndex]);
ko.utils.arrayRemoveItem(self.lowPriorityTasks(), nextItem);
}
}
}
I have a fiddle here that attempts to illustrate the issue I am facing.
To insert an item
at n
th index of an array, you need to call:
array.splice(n, 0, item);
You're calling the splice
function with 4 arguments. Hence items[sourceIndex]
is adding an extra item to the normalPriorityTasks
.
// all parameters after the 2nd get added to the array
array.splice(start, deleteCount, item1, item2, ...)
Remove the forth parameter from the splice
and change your function to:
self.GetNextItemForClass = function(group, sourceIndex) {
var nextItem = ko.utils.arrayFirst(self.lowPriorityTasks(), function(item) {
if (item == null)
return null;
return item.group() === group;
});
if (nextItem != null) {
var items = self.lowPriorityTasks();
// splice works for zero index as well
// remove the forth argument from this call
self.normalPriorityTasks.splice(sourceIndex, 0, nextItem);
self.lowPriorityTasks.remove(nextItem); // use remove
}
}