我已经开发 Backbone 应用程序有一段时间了,并且刚刚开始学习将 Backbone 与 Require.js 一起使用。
在我正在重构的主干应用程序中,我定义了一个这样的命名空间:App.model.repo
. 该模型在不同的视图中反复使用。我对一些集合做同样的事情,例如,App.collection.files
. 这些模型和集合与初始索引文件请求一起引导。
我确实找到了这个示例,这看起来是获取引导数据的好方法。但是,我正在努力寻找在视图之间重用/共享这些模型和集合的最佳方法。
我能想到三种可能的解决方案。哪个最好,为什么?还是我完全错过了另一种解决方案?
解决方案 1
在索引中定义这些公共模块和集合(当它们被引导时),然后将它们作为选项(的initialize
)传递给每个 Backbone 视图。
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
}
});
}
);
就分离而言,这些看起来很干净,但很快就会变得时髦,到处都是大量的东西。
解决方案 2
定义一个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){
}
});
}
);
我担心这会让人对什么是构造函数和什么是实例感到真正的困惑。
结尾
如果你读到这里,你太棒了!感谢您抽出宝贵的时间。