Keeping selection after sort

Hi,

To keep the selection when the grid is changed, I have made 2 functions :

function saveSelRef() {
  grid.selRef = ;
  grid.selection.selected(function (index) {
    if (index != null) {
      grid.selRef.push(grid.items[index]
[0]
);
    }
  });
}

function restoreSelRef() {
  for (var i = 0; i < grid.items.length; i++) {
    if (jQuery.inArray(grid.items[i]
[0]
, grid.selRef) != -1) grid.selection.select(i);
  }
}
[/i]

I use them in the sort event :

grid.addEventListener('sort-order-changed', function() {
  saveSelRef();
  var idx = grid.sortOrder[0]
.column;
  var asc = grid.sortOrder[0]
.direction == 'asc';
  grid.items.sort(function(a, b) {
    var ret;
    if (idx < 5) {
      if (a[idx]
 < b[idx]
) ret = asc ? -1 : 1; else if (a[idx]
 > b[idx]
) ret = asc ? 1 : -1; else ret = 0;
    } else {
      if (parseFloat(a[idx]
) < parseFloat(b[idx]
)) ret = asc ? -1 : 1; else if (parseFloat(a[idx]
) > parseFloat(b[idx]
)) ret = asc ? 1 : -1; else ret = 0;
    }
    return ret;
  });
  restoreSelRef();
});

But, this way, I think restoreSelRef() get called too soon, resulting in no selection restored… I have to put it in a setTimeout of 100ms for it to work.
Is there a better way than an asynchronous call to get the good result ?

Edit : perhaps could you add a then() to the clearCache(), as I use clearCache somewhere else and I have to use a setTimeout again ?

Hi!

To get the behaviour you’re looking for, I think you need to either call restoreSelRef() inside the callback you’ve provided to grid.item.sort (preferably calling the restoreSelRef() only at the last iteration somehow)

OR

by providing the data as a function data source, and then explicitly calling clearCache() (or refreshItems() in latest version) and restoreSelRef() after clearCache() after sorting has happened

OR

by providing the data as a function data source and calling restoreSelRef() inside the data source function after returning the items for the callback.

Let me know how it goes,

Sauli