简体   繁体   中英

ExtJS - Store Ajax response variable as a global

I am trying to store the settings into the global variable.

var settings= {};

function on_ready() {
    Ext.Ajax.request({
         url: baseURL,

         success: function(response) {
             settings = Ext.decode(response.responseText);
         },

         failure: function(response) {
             console.log('server-side failure with status code ' + response.status);
         }
    });
}

console.log(settings);

The last line of code shows empty. I know that this is asynchronous call and thus it does not work. But don't know the solution. Is there a way how can I do this? I need to use this ˙settings˙ variable throughout my application. That's why it has to be global.

One approach we have used in the past for initializing settings before app start was using server-side templating for the html file. It did nothing more, but simply add a <script> block, and populated it with lines like window['prefix_propname'] = 'propvalue'; . Not the most elegant way, but it worked fine.

But first, I'd rethink if you truly need it to be global. It's likely that you could simply have a data field in main's viewmodel with the settings (which are loaded on init of the main's controller), and then bind setting's parts as needed to the children via their config. Logic depending on the settings value then would be either in child's config update / apply methods, expressed via formulas with the settings as one of the parameters, or via a bind (inside view or controller). The bindings inside controller is a very handy feature, which comes up fairly often in my use, and it abstracts away the annoyance of having to deal with async loading; eg:

// view controller
init: function() {
  var vm = this.getViewModel();
  vm.bind('{settings}', function(settings) {
    //do your thing here
  });
}

All you need is a extjs singleton. Get the instance of singleton inside the success function and assign your settings to that singleton. Also there is an easier way to add singleton, ie by adding settings in your window object.

success: function(response) {
             window["settings"] = Ext.decode(response.responseText);
}

Now you should be able to access the settings globally across the application.Still console.log will not have actual value because the will be other thread created for ajax call the present exection will continue without waiting for success function. You type "settings" after execution of "success" you'll see the contents.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM