2

I have a simple translate class (module) which handles the localization for my app. Inside the translate class I am loading the required language modules with a require function.

define(['require', 'config', 'store'],
function(require, Config, Store) {
    // Using ECMAScript 5 strict mode during development. By default r.js will ignore that.
    'use strict';

    var translation = {
        locale: null,
        name: null,
        keys: null,
        timezones: null
    };

    var languageCode = Store.getInstance().get('LanguageCode') || Config.defaultLanguageCode;

    require(['translation/' + languageCode], function(trans) {
        translation = trans;
    });

    var get = function(key) {
        return (!!translation.keys && translation.keys[key]) ? translation.keys[key] : key;
    };

    var timezone = function(key) {
        return (translation.timezones[key]) ? translation.timezones[key] : key;
    };

    return {
        _: get,
        timezone: timezone,
        timezones: function() {
            return translation.timezones;
        }
    };
});

The problem is that the return statement is executed before the needed language has loaded. I put the translate class in the require shim to load it before other modules but that didn't work either.

Erfan Ebrahimnia
  • 262
  • 1
  • 2
  • 9

1 Answers1

-1

I found a solution to your exact problem without using promises. I use a function WaitFor to wait for the module require() dependency to load.

This is how my App module looks like:

define("App", ["Config"], function () {

    var queue = [];
    var fetchingId, cb;

    var App = {
        Dialog: null
    };

    require(["FloDialog"], function () {
        App.Dialog = new FloDialog();
    });

    return {
        WaitFor: function (id, callback) {
            if (!fetchingId) {
                fetchingId = id;
                cb = callback;
                require([id], function () {
                    cb(App);
                });
            } else {
                queue.push([id, callback]);
            }
        }
    };
});

Notice the WaitFor function at the bottom. When I require the module App like you see below I use the WaitFor function to literally wait for the require() dependency to load in the module. When it is ready, in my case, I return a App variable that now contains the App.Dialog var (and is loaded with an instance of the FloDialog class).

On some-page.html:

<script type="text/javascript">
  require(['App'], function (App) {

        App.WaitFor('FloDialog', function(App) {
            console.log(App.Dialog); // Yay! The instance is loaded and good to go!
        });

</script>
Floris
  • 2,727
  • 2
  • 27
  • 47