Monday, January 30, 2012

Refreshing a Dojo DataGrid

Here's a little trick for refreshing the contents of a Dojo DataGrid to the currently selected position. You may wish to do this if your data source is being updated by something else, and you need to force a refresh.

dojo.require("dojo.aspect");
var grid = dijit.byId("myGrid");
grid.store.close();
var handle = dojo.aspect.after(grid, "_onFetchComplete", function() {
    handle.remove();
    this.scrollToRow(this.selection.selectedIndex);
});
grid.sort();

This simplified example closes the store and calls sort() to force a refresh of the data.

In the normal course of processing, Dojo tries to get you back to where you were, but due to the clearing of the data, the scroller height is reduced, and when Dojo tries to set the scrollTop property of the grid div, it remains as it's reset value of 0.  Therefore, we use aspect.after() to set the row after the fetch from the sort has completed.

We don't need this happening every time data is fetched for the grid, so we record the aspect handle, and force the aspect function to remove itself from the chain, once it has been called.  Since the scrollToRow call is likely to fetch more data, we remove the aspect handle before calling it, so we don't have the aspect function called twice.

This was done using Dojo 1.7.1.

No comments:

Post a Comment