我正在使用 Zend 生成我的主视图主机。因此,它是唯一在服务器端进行解析的 HTML。我的服务器知道我想将其一直传递到我的 View 模型之一的配置参数。我不想让 View 模型通过 ajax 请求此数据。
如何让我的 View 通过 main.js、shell 传递数据到 durandal 中的 View 模型?
现在我正在一个令人讨厌的全局中设置值,然后在我的index.phtml的 View 模型中引用该全局:
<script>
//This sucks, but i don't know how to pass stuff down into Durandal yet...
//
window.ServiceRoot = "<?=$this->contentRoot?>";
</script>
在直接 KO 应用程序中,我会将其传递给 KO View 模型构造函数(或设置可观察的属性)。
从技术上讲,我正在使用 durandal 2.0 预发行版,但我认为这并不重要。我想我需要通过 require.js 脚本标记传递参数,就像我传递主参数一样。
最佳答案
我建议您添加一个 config.js 模块来保存“配置”数据。添加初始化函数以从服务器获取配置数据并将其缓存。
然后...在 shell.js 的 activate 函数中,在绑定(bind) View 之前初始化配置。
然后,您可以在所有 View 模型中要求您的配置模块,它只会返回缓存的数据。
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;
});
我知道你说过你不想通过ajax加载数据,但是使用这种方法,你只会加载一次并重新使用它。如果需要,您还可以加载额外的配置。这使用单一职责原则很好地分离了代码。
编辑:
如果您确实需要在渲染的页面中执行此操作,您可以按照以下方式执行操作:
<script>
var myapp = myapp || {};
myapp.config= (function() {
var contentRoot = "<?=$this->contentRoot?>";
return {
contentRoot: contentRoot
};
})();
</script>
然后,在 main.js 中,在定义主模块之前,您可以使用以下方法将其短路:
define('appconfig', [], function () { return myapp.config; });
然后,您可以像平常一样在 View 模型中调用 appconfig 模块,并使用 appconfig.contentRoot 访问 contentRoot。
关于zend-framework - Durandal:如何将配置数据从 HTML Host 传递到 ViewModel?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17799521/