23 Jan 2012

Firing an event after updating a DataGrid's data store in Dojo

Currently I find myself struggling with Dojo. It's rather sparsely documented and I regularly have to plow through the web to find out how to get something done. I might as well document some of my findings here, so other people (and myself because I might forget) can benefit from it.

In this case the issue was that I had a Dojo DataGrid, and I wanted to do something after every (re)load of its datastore. For the example's sake, suppose I wanted to run the following JavaScript function:


function doThisAfterLoadingDataStore()
{
  alert('DataStore has been (re)loaded!');
}
Of course the data store's fetch() method has an onComplete event, but to fire that event, I would have to explicitly call fetch(). This would be a waste of bandwidth, because the data store's data has already been fetched since I declaratively specified the store in the DataGrid, which causes an automatic fetch (without a specifyable onComplete event). It would have been great if there were an event onFetchComplete for the DataGrid, but unfortunately in the version of Dojo that I'm using (1.6), this is not the case. It does have an event _onFetchComplete, but this is a private event, and can't be specified declaratively in HTML (which is what I wanted to do). Luckily it can be specified in JavaScript with the dojo.connect method, so I managed to do it in the following way:
  1. I declaratively specified a postCreate method for my datagrid:
    
    <table ... dojoType="dojox.grid.DataGrid" ... postCreate="gridPostCreate">...</table>
    
  2. This postCreate method calls dojo.connect to specify the _onFetchComplete event (and also makes sure the base postCreate is called):
    
    function gridPostCreate()
    {
      dojo.connect(this, "_onFetchComplete", doThisAfterLoadingDataStore );
      this.inherited("postCreate", arguments);
    }
    
This did the trick. Now let's hope the _onFetchComplete event will continue to work like this in future Dojo versions...

No comments:

Post a Comment