我试图围绕 Backbone,更具体地说,应用程序如何在其整个生命周期中流动。不幸的是,在我的工作中,我无法访问(或就此而言)我们的 API 是如何构建的。我们有来自不同时间段的许多不同的调用,它们的结构非常不一致。
覆盖 fetch 或 sync 不是标准化返回的问题,但我遇到的问题(在我开始研究 Backbone 应用程序时)是如何布局实际代码。
这是我在现实世界中的例子。这个页面是非关键的,我正在尝试用 Backbone 重写它。这是流程:
- 页面从通话中加载流派类型列表
- 单击流派类型会根据流派类型加载子流派(子流派类型需要流派代码作为参数)
- 单击子流派类型会加载具有该标准的所有产品。
我可以走得很远,但在某些时候我觉得代码被弄乱了——或者感觉不自然。就像我在推东西一样。
所以我的官方问题是:如何管理 Backbone 应用程序?
以下是我的流程总结:
我应该创建一个全局命名空间
var App = App || {};
好的,让我们从主应用程序视图开始,所有示例都显示:
App.MainView = Backbone.View.extend({
//this loads the outer stuff
//and creates an instance of the Genre View
});
好吧,很简单,我需要一个流派模型、集合和视图(这也适用于子流派)
App.Genre = Backbone.Model.extend();
App.Genres = Backbone.Collection.extend({
url: 'returns a list of genres',
model: App.Genre,
initialize: function() {
this.fetch();
},
fetch: function() {
var self = this;
$.ajax({
url: this.url,
success: function(response) {
**format return**
self.add(formattedArrayOfModels);
}
});
}
});
现在来看视图,令人困惑的部分
App.GenreView = Backbone.View.extend({
el: 'element',//easy enough
tmpl: 'my handlebars template',//implementing handlebars...no problem
initialize: function() {
//this produces a collection full of genres
this.genreList = new App.Genres();
this.genreList.on('add', _.bind(this.render, this));
},
render: function() {
//rendering not a problem, pretty straight forward
}
});
直到这里我没有问题。流派列表加载,我们很高兴。所以,现在当用户点击一个流派时,我希望它加载一个子流派
events: {
'click a': 'getSubGenres'
},
getSubGenres: function(e) {
}
这是我的问题。在getSubGenres中,我是否将其保留在本地?
var subGenre = new App.SubGenreView();
或者我应该让它成为流派视图的一部分?
this.subGenre = new App.SubGenreView();
我应该以某种方式将它放在父对象中,以便其他视图可以访问它吗?我如何控制这样的事情?
如果我已经有一个子类型的集合,我该如何使用加载的集合(而不是另一个 ajax 调用)。
这是你会使用的方法吗?