我已经开发 Backbone 应用程序有一段时间了,并且刚刚开始学习将 Backbone 与 Require.js 一起使用。
在我正在重构的主干应用程序中,我定义了一个这样的命名空间:App.model.repo
.该模型在不同的 View 中反复使用。我对一些集合做同样的事情,例如,App.collection.files
.这些模型和集合与初始索引文件请求一起引导。
我确实找到了 this example ,这看起来是获取引导数据的好方法。但是,我正在努力寻找在 View 之间重用/共享这些模型和集合的最佳方法。
我能想到三种可能的解决方案。哪个最好,为什么?还是我完全错过了另一种解决方案?
解决方案一
在索引中定义这些公共(public)模块和集合(当它们被引导时),然后将它们作为选项(initialize
)传递给每个 Backbone View 。
define(['jquery', 'underscore', 'backbone', 'handlebars', 'text!templates/NavBar.html'],
function($, _, Backbone, Handlebars, template){
return Backbone.View.extend({
template: Handlebars.compile(template),
initialize: function(options){
this.repoModel = options.repoModel; // common model passed in
}
});
}
);
就分离而言,这些看起来很干净,但很快就会变得时髦,到处都是大量的东西。解决方案二
定义一个
globals
模块,并在其中添加常用的模型和集合。// models/Repo.js
define(['backbone'],
function(Backbone){
return Backbone.Model.extend({
idAttribute: 'repo_id'
});
}
);
// globals.js (within index.php, for bootstrapping data)
define(['underscore', 'models/Repo'],
function(_, RepoModel){
var globals = {};
globals.repoModel = new Repo(<?php echo json_encode($repo); ?>);
return globals
}
);
define(['jquery', 'underscore', 'backbone', 'handlebars', 'text!templates/NavBar.html', 'globals'],
function($, _, Backbone, Handlebars, template, globals){
var repoModel = globals.repoModel; // repoModel from globals
return Backbone.View.extend({
template: Handlebars.compile(template),
initialize: function(options){
}
});
}
);
这个解决方案是否打败了 AMD 的全部观点?解决方案3
让一些模型和集合返回一个实例,而不是一个构造函数(有效地使它们成为单例)。
// models/repo.js
define(['backbone'],
function(Backbone){
// return instance
return new Backbone.Model.extend({
idAttribute: 'repo_id'
});
}
);
// Included in index.php for bootstrapping data
require(['jquery', 'backbone', 'models/repo', 'routers/Application'],
function($, Backbone, repoModel, ApplicationRouter){
repoModel.set(<?php echo json_encode($repo); ?>);
new ApplicationRouter({el: $('.site-container')});
Backbone.history.start();
}
);
define(['jquery', 'underscore', 'backbone', 'handlebars', 'text!templates/NavBar.html', 'models/repo'],
function($, _, Backbone, Handlebars, template, repoModel){
// repoModel has values set by index.php
return Backbone.View.extend({
template: Handlebars.compile(template),
initialize: function(options){
}
});
}
);
我担心这会让人对什么是构造函数和什么是实例感到真正的困惑。结束
如果你读到这里,你太棒了!感谢您抽出宝贵的时间。
最佳答案
就我而言,我更喜欢 选项 3 .虽然,为了防止混淆,我将每个单例实例放在他们自己的文件夹中,名为 instances
.另外,我倾向于将 model/collection
分开。来自 instance
模块。
然后,我只是调用他们:
define([
"instance/photos"
], function( photos ) { /* do stuff */ });
我更喜欢这个选项,因为每个模块都被迫定义其依赖项(例如,通过命名空间不是这种情况)。解决方案 2 可以完成这项工作,但如果我使用的是 AMD,我希望我的模块尽可能小——再加上保持它们小,以便更容易进行单元测试。
最后,关于单元测试,我可以在单元测试中重新定义实例以使用模拟数据。所以,当然,选项3。
您可以在我正在开发 ATM 的开源应用程序上看到此模式的示例:https://github.com/iplanwebsites/newtab-bookmarks/tree/master/app
关于backbone.js - Backbone/Require Application 中共享对象的最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14882836/