2012-10-06 60 views
2

我正在嘗試在現有項目中使用requireJS。我有一個具有關於當前的區域設置,URL信息的應用模塊......並希望加載另一個模塊,如果目前的語言環境是一些特別的東西:確保requireJS條件模塊已加載

// 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 
    }; 
}); 

現在的問題是我不知道什麼時候應用程序模塊加載number方法。如果我確定locale/fa模塊應該加載在某個點上,我可以使用require(['locale/fa']或使用墊片包裝它。目前我使用舊的阻止方式來加載合適的locale/*.js和PHP來選擇正確的文件,沒有問題。但我想知道如何requireJS程序員編寫類似的代碼。可能有一些比這個代碼更好的方法:

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

回答

2

這聽起來像是一個案例爲i18n plugin!我相信你可以定義函數和字符串。我將定義一個包,像這樣:

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

而且這裏是你的波斯覆蓋:

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

在你app.js文件:

require(['app','i18n!nls/formatters'], function(App, Formatters) { 
    Formatters.currency(5.00); // works! 
}); 
+0

謝謝,這是絕對有用的,但我的問題更通用,而不僅僅是本地化。順便說一句,如果沒有人提出更通用的方法,我會接受你的答案。 (我的問題是我不知道哪個本地化應該被加載,直到'App'構建完成。使用'i18n!'我應該在'App'加載之前設置區域設置。) – Reith

+0

插件訪問navigator.language屬性,用戶計算機上的語言環境!如果這不適合你的使用,你可以創建一個指定它的build.js文件。儘管如此,爲了更一般地回答你的問題,有條件的要求*出現*起作用,但實際上會導致需要所有代碼分支(假設你需要(「」)字符串,而不是預設變量。) – zetlen

+0

'navigator。 language'(這是隻讀的AFAIK)或'build.js'不能解決任何問題,因爲它們都在'require.config'之前設置了locale。沒有辦法改變語言環境[之後](https://github.com/jrburke/requirejs/issues/213)。 – Reith