Pages

Thursday, September 9, 2010

Setting the scope of callbacks with Extjs

I recently ran into a problem where I was attempting to access a record in a collection being iterated over from inside a GDownloadUrl (Google Maps API) callback whose request would be executed as part of that loop. It took me a while to figure out the reason the last record was always getting passed to the callback no matter which callback was executing - GDownloadUrl is asynchronous and by the time any of the callbacks are executed the iteration was usually over!

Extjs provides an easy alternative to GDownloadUrl that allows access to the iteraiton record (or any other object) used when executing the callback - Ext.Ajax. All that needs to be done to retain the object required in the callback is to call createDelegate on the callback and then access the object in the callback using "this". An example is provided below:

for (var i = 0; i < activeLayersStore.getCount(); i++) {

    var record = activeLayersPanel.getStore().getAt(i);

    Ext.Ajax.request({
        url: url,
        timeout        : 180000,
        success: function(response, options) {
        alert("The record for this iteration is: "+ this.get('TypeName'));
        }.createDelegate(record),
        failure: function(response, options) {
            alert("Error requesting data" + response.statusText);
        }
    });

}

The documentation for Extjs Function.createDelegate can be found here: http://dev.sencha.com/deploy/dev/docs/?class=Function&member=createDelegate

Additionally,  if multiple objects are required for use in the callback, the createDelegate may be used as follows:


yourFunction.createDelegate({ o1: obj1, o2: obj2 });

or alternatively, if the signature of your handler is flexible you can pass parameters as follows:
yourFunction.createDelegate(scope, [scope2], 2); 

0 comments:

Post a Comment

 
Powered by Blogger