PDA

View Full Version : scope problem with combo callback



7 Nov 2011, 7:54 PM
I have a set of Combo Boxes which are dynamically loaded using the following code:



for(var i = 0 ; i < strata.item.length; i++) {
var s_id = strata.item[i].stratum_id;
var combo = Ext.getCmp('strata'+s_id+'_combo');
comboCallback = function(){
alert( s_id );
};
combo.store.load({
callback: comboCallback
});
}


I have some more code to put in the callback but first I need to work out why it brings up '2' both times the callback is run. I'm guessing it has to do with the asynchronous loading of the store, but I'm not sure how to refer to the in-loop value of s_id (or even i) from within the callback.
Thanks.

skirtle
8 Nov 2011, 2:07 AM
The function comboCallback will form a closure on s_id. In other words, it will have a live reference to the variable. By the time the callback is called (asynchronously, as you say) the value of s_id will be the last value it was assigned in the loop.

There are a number of ways to remedy this and without knowing a little more about your code it's difficult to say for sure what the best way is. Here's one way:


Ext.each(strata.item, function(item) {
var s_id = item.stratum_id;

var combo = Ext.getCmp('strata' + s_id + '_combo');

var comboCallback = function(){
alert( s_id );
};

combo.store.load({
callback: comboCallback
});
});