2

我正在尝试在现有项目中使用 requireJS。我有一个 App 模块,其中包含有关当前语言环境、url 的信息……如果当前语言环境很特殊,我想加载另一个模块:

// App.js
define([], function() {
    return {
        setEnv: function(obj) { //obj: {locale:'en'}
            this.env = obj;
            that = this;
            if( this.env.locale == 'fa' )
                require(['locale/fa'], function(fa) {
                    that.number = fa.number
                };
            else
                this.number = function( n ) { return n+'' }
        }
    }
});

语言环境文件如下:

// locale/fa.js
define([], function() {
    var enToFaDigit(n) { // a function converts a number to persian representation };
    // more stuff
    return {
        number: enToFaDigit
    };
});

现在的问题是我不知道 App 模块何时加载number方法。如果我确定locale/fa模块应该在某个时候加载,我可以使用require(['locale/fa']或使用 shim 来包装它。目前我正在使用旧的阻塞方式来加载适当的locale/*.js和 PHP 来选择正确的文件,没有问题。但我想知道 requireJS 程序员如何编写类似的代码。可能有比这段代码更好的方法:

require(['app'], function(App) {
    if(App.env.locale == 'fa') {
        require(['locale/fa'], function(fa) {
            // 8-S
        }
    }
});
4

1 回答 1

2

This sounds like a case for the i18n plugin! I believe you are allowed to define functions as well as strings. I would define a bundle like so:

//nls/formatters.js
define({
    root: {
        currency: function(num) {
            // implementation for default currency format (en-US often)
        }
    },
    "fa": true
})

And here's your Persian override:

//nls/fa/formatters.js
define({
    currency: function(num) {
        // implementation for farsi currency format
    }
})

In your app.js file:

require(['app','i18n!nls/formatters'], function(App, Formatters) {
    Formatters.currency(5.00); // works!
});
于 2012-10-07T02:24:28.730 回答