我有一个简单的翻译类(模块(来处理我的应用程序的本地化。 在翻译类中,我正在使用require函数加载所需的语言模块。
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;
}
};
});
问题是 return 语句是在加载所需语言之前执行的。我将翻译类放在需要填充程序中以在其他模块之前加载它,但这也不起作用。
我在不使用承诺的情况下找到了解决您确切问题的方法。我使用函数WaitFor
来等待模块require()
依赖项加载。
这是我的应用模块的样子:
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]);
}
}
};
});
请注意底部的WaitFor
函数。当我需要如下所示的模块应用程序时,我使用 WaitFor
函数从字面上等待require()
依赖项加载到模块中。当它准备就绪时,就我而言,我返回一个 App 变量,该变量现在包含 App.Dialog var(并加载了 FloDialog 类的实例(。
在某些页面上.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>