开发者

javascript Scope issue in Ext.Ajax.request

开发者 https://www.devze.com 2023-04-05 09:28 出处:网络
I have this class which automatically generates JSON stores from server. Stores are created on the fly and are viewable in Firebug\'s DOM.

I have this class which automatically generates JSON stores from server. Stores are created on the fly and are viewable in Firebug's DOM. I think i have some scope issues.When i want to console.log(Ext.getStore('AdminSettings')) (which AdminSettings is one of the created stores) inside Ext.Ajax.request`s callback function, 'AdminSettings' store is returned but if i put console.log(Ext.getStore('AdminSettings')) everywhere outside callback function,i get undefined message in firebug and my store is not instantiated. See code comments to see it in action.

Ext.Ajax.request({
url : './account/getadminstores',
callback : function(options, success, response) {
var json = Ext.decode(response.responseText);
var adminStores = new Array();
// setup and intitialize on the fly stores
for ( var key1 in json) {
var storeFields = new Array();
for ( var key2 in json[key1]) {// if (i==1){break;}
for ( var key3 in json[key1][key2]) {
storeFields.push(ke开发者_高级运维y3);}
break;};
Ext.define('MA.store.' + key1, {
extend : 'Ext.data.Store',
fields : storeFields,
storeId : key1,
data : json[key1]
});
Ext.create('MA.store.'+key1);};
console.log(Ext.getStore('AdminSettings'));
//returns MA.store.AdminSettings in firebug and everything is fine 
                }
            });//eof Ext.Ajax.request
            console.log(Ext.getStore('AdminSettings'));
//returns undefined which is strange


Ext.Ajax.request is asynchronous. Your final console.log call returns nothing because at the time it is executed the request has not yet completed. Any code depending on the results of the request's callback will need to be executed by the callback as well.


This is due to the asynchronous nature of javascript, callback doesn't get called until after the ajax request finishes, so the Ext data store doesn't get defined either.

The order of execution of your script is:

  1. Ajax request is initialized
  2. console.log is executed (undefined since the datastore hasn't been defined yet)
  3. javascript is waiting for an ajax response from ./account/getadminstores
  4. response comes in, callback function is called (which defines the data store)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号