开发者

Proper ways to handle asynchronous functions

开发者 https://www.devze.com 2023-02-14 04:31 出处:网络
Note: If you think this post should have a better title, please tell me/edit it! I am trying to internationalize an ExtJS form I have created.I have the javascript for my form in one file and the tra

Note: If you think this post should have a better title, please tell me/edit it!

I am trying to internationalize an ExtJS form I have created. I have the javascript for my form in one file and the translations in another javascript file like this:

english.js

function get_i18n(){

    var i18n = {  
        Apply                               : 'Apply For Scholarship',
        Student_Information                 : 'Student Information',
        First_Name                          : 'First Name',  
        Last_Name                           : 'Last Name',  
        Gender                              : 'Gender',  
        Male                                : 'Male',  
        Female                              : 'Female',
    }  

    return i18n;
}

Then in my form.js

function getLang(){
     // decode language passed in url
   var locale = window.location.search 
                ? Ext.urlDecode(window.location.search.substring(1))
                : '';
   return locale['lang'];
}//end getLang()

var form;

var lang = getLang();
var languageFile;

if (lang == 'chn'){
    languageFile = "chinese.js"; 
}
else if (lang == 'eng'){
    languageFile = "english.js";
}
else if (lang == 'tib'){
    languageFile = "tibetan.js"; 
}

function getLabels(file){
    var a = $.getScript(file, function(){
    var b = get_i18n();
    return b;
});
return a;
}//end getLabels()

var i18n = getLabels(languageFile);

Ext.onReady(function(){
    Ext.QuickTips.init();
        form = new Ext.form.FormPanel({
        id: 'scholarshipForm',
        labelWidth: 200, // label settings here cascade unless overridden
        url:'scholarshipSubmit.php',
        method: 'POST',
        frame:true,
        layout: 'form',
        title: 'Apply For Scholarship',
        bodyStyle:'padding:10px 10px 0',
        width: 610,
        itemCls: 'formStyle',
        items: [{
            xtype:'fieldset',
            checkboxToggle:false,
            title: 'Student Information',
            autoHeight:true,
            layout: 'form',
            defaults: {width: 210},
            collapsed: false,
            items :[{
                    xtype: 'textfield',
                    fieldLabel: i18n['First_Name'],  //RIGHT HERE I TRY TO USE THE RESULTS
                    allowBlank:false,
                    name: 'first', 
                    maskRe: /([a-zA-Z\s]+)$/,
                    msgTarget: 'side'
                }
...
...
...
        form.render(document.body);

});

Having played with the code a bit I know my problem probably has something to do with the way I am handling the asynchronous jQuery $.getScript. The weird thing is that when I did not try to get the language from the url get variable and instead ran my getLabels function by giving the filename directly to the $.getScript inside it, I got the desired results and the labels of my form displayed accordingly. I'd really appreciate any help with this. I am still new to asynchronous calls and they always 开发者_JAVA技巧get me stuck :-/. I thought that having $.getScript inside another function and bubbling up the return like that would solve the issue and perhaps it does, as like I mentioned earlier it worked fine until I added the logic for getting the file name based on the url $_GET.

Thank you for your time,

elshae

EDIT

Now I have a english.json

{i18n: {  
        "Apply"                             : 'Apply For Scholarship',
        "Student_Information"               : 'Student Information',
        "First_Name"                        : 'First Name',  
        "Last_Name"                         : 'Last Name',  
        "Gender"                            : 'Gender',  
        "Male"                              : 'Male',  
        "Female"                            : 'Female'
}
}

and I'm trying to do this:

var i18n = {};
function getLabels(file){

    $.getJSON(file, i18n, function(data) { i18n = data.i18n; return i18n;});
    return true;
}
getLabels(languageFile);

I need to get a i18n object out of that callback function which I can use like this: i18n.First_Name etc


You cannot return a value from a callback handler like that. Well, you can if you want, but it doesn't do any good.

Instead, the simplest thing to do is to just rearrange the code so that all the stuff you need to do after that ".getScript()" finishes is code right there inside the callback function.

So, something like:

function getLabels(file){
    $.getScript(file, function(){
       var i18n = get_i18n();

       Ext.onReady(function() {
         // all that stuff
       });
    });

}//end getLabels()

I don't know Ext.js at all so I'm not sure whether that "onReady" call would be the right thing to do. The point is that inside your ".getScript()" callback, you can reliably use the code in the script you fetched.


Perhaps instead of putting your language code in a javascript function, why not put it into a JSON formatted file, which would allow you to use the jQuery functions to load the JSON into a proper object, and your code can use that instead.


Ajax is asynchronous, meaning you can't return a value from a callback function.

You can however provide another callback function as a parameter. That callback will then executed with your required data as a parameter.

var i18n = {};
function getLabels(file, callback){
      $.getJSON(file, i18n, function(data) {
          i18n = data.i18n;
          callback(i18n);
      });
      return true;
}


getLabels(languageFile, function(i18n) {
    // do something with the data
});
0

精彩评论

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