如何在使用AMD(require.js)加载自举模式Backbone.js的中 [英] How to load bootstrapped models in Backbone.js while using AMD (require.js)
问题描述
Backbone.js的文档加载建议自举模式是这样的:
Backbone.js documentation suggest loading bootstrapped models this way:
<script>
var Accounts = new Backbone.Collection;
Accounts.reset(<%= @accounts.to_json %>);
var Projects = new Backbone.Collection;
Projects.reset(<%= @projects.to_json(:collaborators => true) %>);
</script>
但是,这是不能被使用的模式 AMD的做法(使用require.js)
惟一可行的办法是声明的全局变量存储JSON数据并使用这个变量后面的相关初始化方法。
The only possible solution is to declare global variable storing JSON data and use this variable later in relevant initialize methods.
有一个更好的办法,以做到这一点(不带全局)?
Is there a better way to do this (without globals)?
推荐答案
这就是我们的方式,它不污染全局命名空间引导数据。相反,它使用专门require.js。它还可以帮助您提供基于模板中变量的初始应用程序配置。
This is how we bootstrap data in a way that it doesn't pollute the global namespace. Instead it uses require.js exclusively. It also helps you provide the initial app configuration based on variables within the template.
<script src="require.js"></script>
<script>
define('config', function() {
return {
bootstrappedAccounts: <%= @accounts.to_json %>,
bootstrappedProjects: <%= @projects.to_json(:collaborators => true) %>
};
});
</script>
<script src="app.js"></script>
globals.js
有关配置此文件检查,并扩展自己使用的任何数据退换
globals.js
This file checks for config and extends itself using any of the data returned
define([
'config',
'underscore'
], function(config) {
var globals = {
};
_.extend(globals, config);
return globals;
});
config.js
如果您希望能够加载应用程序,无论如果你定义在页面配置
的需要此文件。
define(function() {
// empty array for cases where `config` is not defined in-page
return {};
});
app.js
require([
'globals',
'underscore',
'backbone'
], function(globals) {
if (globals.bootstrappedAccounts) {
var accounts = new Backbone.Collection(globals.bootstrappedAccounts);
}
if (globals.bootstrappedProjects) {
var projects = new Backbone.Collection(globals.bootstrappedProjects);
}
});
这篇关于如何在使用AMD(require.js)加载自举模式Backbone.js的中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!