将引导变量和 JSON 传递给 require.js
将渲染页面中的引导变量(即 JSON 数据或配置变量)传递到 require.js
以便检查它们是否被依赖项使用的最佳实践是什么?
看起来这可以通过检查 window
对象(即 window.bootstrapped_models
)来完成,但这似乎不是很理想。
app.html
- HTML 文档
<script>
var config = {
"isAdmin": true,
"userId": 1
};
var bootstrapped_models = {
"groups": [
{
"id": 1,
"name": "Foo"
},
{
"id": 2,
"name": "Bar"
}
]
}
</script>
app.js
中的示例数据 - 使用 require() 的示例应用程序
require(['jquery', 'GroupCollection'], function($, GroupCollection) {
// extend default config
if (config) {
$.extend(defaults, config);
}
// use bootstrapped JSON here
var collection = new GroupCollection;
if (bootstrapped_models.groups.length > 0) {
collection.add(bootstrapped_models.groups);
}
});
What is the best practice for passing bootstrapped variables within the rendered page (i.e. JSON data or config variables) to require.js
so they can be checked for an used by dependancies?
It looks like this could be done by checking the window
object (i.e. window.bootstrapped_models
but that does not seem very optimal.
app.html
- example data within the HTML document
<script>
var config = {
"isAdmin": true,
"userId": 1
};
var bootstrapped_models = {
"groups": [
{
"id": 1,
"name": "Foo"
},
{
"id": 2,
"name": "Bar"
}
]
}
</script>
app.js
- example app using require()
require(['jquery', 'GroupCollection'], function($, GroupCollection) {
// extend default config
if (config) {
$.extend(defaults, config);
}
// use bootstrapped JSON here
var collection = new GroupCollection;
if (bootstrapped_models.groups.length > 0) {
collection.add(bootstrapped_models.groups);
}
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
@timDunham 的答案很有帮助,但对我来说有点过于复杂。通过使用 require.js 和 Lithium (PHP MVC),我得出了以下结论。它很简单,并且在我遇到的每个实例中都有效。
然后可以通过执行以下操作来获得:
显然,我引入数据的方式是特定于语言的,但无论您的情况如何,其余的都应该有用。
The answer from @timDunham was helpful, but it felt a little overly complicated to me. Playing around with require.js and Lithium (PHP MVC) I came up with the following. It's simple and has worked in each instance I've run into.
Which is then available by doing the following:
Obviously the way I'm bringing the data in is language specific, but the rest should be useful regardless of your situation.
不确定我的方法是否是最佳实践,但我做的事情很像你正在做的事情,除了不是将引导模型对接在全局对象上,而是在我的 HTML 页面中为其创建一个定义:
然后我有一个名为 <其他模块可能需要的 code>current.model ,如下所示:
Not sure if my method is best practice but I do something a lot like what you are doing except instead of butting the bootstrapped models on the global object, I create a define for it in my HTML page:
then I have a js file called
current.model
that can be required by other modules and looks like this:您可以通过禁用 build.js 中的 bootstrapData 来解决优化/构建问题
像这样:
You can solve problems with optimize/build by disabling the bootstrapData in your build.js
Like this: