使用 AMD (require.js) 时如何在 Backbone.js 中加载引导模型 [英] How to load bootstrapped models in Backbone.js while using AMD (require.js)

查看:27
本文介绍了使用 AMD (require.js) 时如何在 Backbone.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

如果您希望能够加载应用程序,无论您是否在页面中定义了 config,都需要此文件.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆