简体   繁体   中英

javascript inline callback function to separate function

Why is this code working:

function onCordovaReady() { 
    navigator.globalization.getLocaleName(function (locale) {
        jQuery.i18n.properties({
            name:'message', 
            path:'lang/', 
            mode:'map',
            language:locale.value,
            callback: function(){
                alert(locale.value);
                alert(jQuery.i18n.prop('msg_hello'));
                alert(jQuery.i18n.prop('msg_complex', 'John'));
            }
        });
    });
}

And this one not:

function onCordovaReady() { 
    navigator.globalization.getLocaleName(function (locale) {
        jQuery.i18n.properties({
            name:'message', 
            path:'lang/', 
            mode:'map',
            language:locale.value,
            callback: onLanguageReady(locale)
        });
    });
}

function onLanguageReady(locale) {
     alert(locale.value);
     alert(jQuery.i18n.prop('msg_hello'));
     alert(jQuery.i18n.prop('msg_complex', 'John'));    
}

I want to make the callback in a different function so my code will look cleaner, but couldn't get it to work. The first alert will work (it will display nl_NL), but the second and third alert will output [msg_hello] and [msg_complex].

Many thanks!

it is because you are assigning undefined to the callback property.

You are calling onLanguageReady and assigns that value to the callback method.

The solution is to use another function as callback function which will call the onLanguageReady function as given by @romainberger

Try with this:

// beginning of code omitted
callback: function(locale) {
    onLanguageReady(locale)
}
function onCordovaReady() { 
    navigator.globalization.getLocaleName(function (locale) {
        jQuery.i18n.properties({
            name:'message', 
            path:'lang/', 
            mode:'map',
            language:locale.value,
            callback: onLanguageReady
        });
    });
}

function onLanguageReady(locale) {
     alert(locale.value);
     alert(jQuery.i18n.prop('msg_hello'));
     alert(jQuery.i18n.prop('msg_complex', 'John'));    
}

will work if the function calls back with locale.

the callback is expecting a function pointer that it can call once the processing is done when you say onLanguageReady(locale) you are actually executing the function and thus assigning the result of the function as the call back in this case the return is nothing thus undefined

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