Search code examples
javascriptjqueryknockout.jskogrid

How to prevent kogrid to automatically select newly added items, preserving current selection?


I've following issue: I have two kogrids on my page. One one the left, one on the right side.

Between them I added two buttons so that the user can move selected items from the left to the right side and the other way round.

Therefor my view model has 4 arrays, ItemsA, SelectedItemsA, ItemsB and selectedItemsB. The two kogrids are configured as followed:

<div data-bind="koGrid: {
data: ItemsA,
selectedItems: SelectedItemsA,
displaySelectionCheckbox: false,
enableRowReordering: true,
enableSorting: false,
columnDefs: [
{ field: 'Name', cellTemplate: tableCellTemplate, cellClass: 'player-row' },
    { field: 'ClubName', displayName: 'Mannschaft' },
    { field: 'DisplayPosition', displayName: 'Position', cellTemplate: playerPositionNameTemplate}
],
footerVisible: false
}">
</div>

On moving items from left to the right, I will push every item from SelectedItemsA into ItemsB via:

$.each(self.SelectedItemsA(), function(idx, player) {
    self.ItemsB.push(player);
});

And cleaning the selection on the left side via:

self.ItemsA.removeAll(self.SelectedItemsA());

They items will appear correctly in the grid on the right side bounded to ItemsB, but they are automatically selected. So if I want to move a single item back, I first have to deselect all items I moved previously! How can I prevent kogrid from automatically selecting newly added items?


Solution

  • Its a bug in koGrid.

    In koGrid-2.1.1.debug.js:

    self.setRenderedRows = function (newRows) {
        self.renderedRows(newRows);
        self.refreshDomSizes();
    };
    

    newRows is an array of the rows you selected / copied. koGrid copies them as they are, that means, that newRows.selected() (observable) is true.

    UPDATE

    Turns out, the above change would also de-select rows after they scrolled out of vision range. But i figured you can just set __kg_selected__ to false for each row you want to copy.

    Say:

    ko.utils.arrayForEach(self.SelectedItemsA(), function(player) {       
        player.__kg_selected__ = false;     
    });
    

    and then push them all to the new array:

    ko.utils.arrayPushAll(self.ItemsB(), self.SelectedItemsA());