我建議你添加一個config.js模塊來保存你的「配置」數據。添加一個初始化函數以從服務器獲取配置數據並緩存它。
然後...在你的shell.js的激活函數中,在綁定你的視圖之前初始化配置。
然後,您可以在您的所有視圖模型中要求您的配置模塊,並且它只會返回緩存的數據。
config.js
define(['dataaccessmodule'], function (dataaccessmodule) {
var config =
{
serviceRoot: null,
init: init
};
var init= function()
{
// get config from server and set serviceRoot;
// return a promise
};
return config;
});
shell.js
define([... your required modules..., 'config'],
function (..., config) {
function activate() {
return config.init().then(boot);
};
function boot() {
// set up routing etc...
// activate the required route
return router.activate('home');
};
});
someViewModel.js
define([... your required modules..., 'config'],
function (..., config) {
var someViewModel =
{
serviceRoot: config.serviceRoot
};
return someViewModel;
});
我知道你所述T您不希望通過ajax加載數據,但使用這種方法,您只需加載一次並重新使用它。如果需要,您也可以加載額外的配置。這很好地使用單一職責原則分離代碼。
編輯:
如果你真的需要做的是在渲染頁面,你可以沿着這些路線做一些事情:
<script>
var myapp = myapp || {};
myapp.config= (function() {
var contentRoot = "<?=$this->contentRoot?>";
return {
contentRoot: contentRoot
};
})();
</script>
然後,在你main.js,定義之前主模塊,可以短路它使用:
define('appconfig', [], function() { return myapp.config; });
然後,您可以要求您的視圖模型了AppConfig模塊,你通常W¯¯應該使用appconfig.contentRoot訪問contentRoot。
thx的詳細迴應,如果它不符合我的條件,它會工作得很好。但是我不能通過ajax從服務器「獲取」我的配置,因爲配置是服務器URL本身。該應用程序託管在各種主機/路徑/子路徑上,因此知道服務根URL的唯一可靠方法就是服務器本身。這就是爲什麼Ajax技術不適合我的原因。如果可能的話,我想避免在JS中使用發現邏輯。 –
看我的編輯。我希望有所幫助。 –
你編輯的回覆有點怪異,但是那麼我的超級全球黑客就少得多了。你能不能在主機頁面做定義權利? –