【发布时间】:2014-03-05 21:27:04
【问题描述】:
我对何时何地实例化集合并在主干应用程序中获取它们感到有些困惑。
我现在已经看到它以几种方式完成,并且在我非常简单的小型 CRUD 联系人管理器应用程序中工作,我正在搞乱,但我确信有一些约定和“陷阱”我不是知道。
这些是我看过的选项,要么开始工作,要么有点“工作”:) 选项 4 在概念上似乎是最好的,但我把它搞砸了。
坏主意:1) 在我真正对路由器做任何事情之前,我实例化了一个新集合并调用 fetch,然后在 doc ready 语句中启动 app.view。
// Create an Instance of the collection
App.contacts = new App.Collections.Contacts;
App.contacts.fetch({update: true, remove: false}).then(function() {
new App.Views.App({ collection : App.contacts });
});
- 这行得通 - 但如果我要在一个应用中拥有多个集合,这似乎不是正确的方法,我认为这个想法失败了。
坏主意:2)当我开始使用路由器时,我想在路由器初始化方法中执行与上述相同的操作,这也有效,但我认为给我留下了同样的问题。
坏主意:3)我尝试在集合 init 方法中获取,尽管我在很多地方读到这似乎是一个坏主意。
好主意(?):但我不能让它工作:4)我认为,当我实例化它的视图时获取集合的数据是有意义的,这样如果我有一个联系人集合和一个任务集合,每个集合只有在我在路由器中实例化其视图时才会从服务器中提取。这对我来说似乎是成功的公式,但是当我尝试将其放在 View init 或渲染方法中时,我的this.collection.on('add', this.addOne, this); 让我无法在未定义时调用 .on。 (注意:我试着把它放在成功函数中)
这让我很头疼,请帮忙。
干杯。
编辑:附加代码,因此我们可以诊断下面讨论的双重负载。
在我的路由器文件中,我使用了这个实用程序 obj:
var ViewManager = {
currentView : null,
showView : function(view) {
if (this.currentView !== null && this.currentView.cid != view.cid) {
this.currentView.remove();
}
this.currentView = view;
return view;
}
}
在我的路由器中:我正在路由上调用此方法
list: function() {
console.log('backbone loading list route');
var AllContactsView = new App.Views.Contacts({ //init method runs now
collection : App.contacts
});
ViewManager.showView(AllContactsView);
},
我的收藏
App.Collections.Contacts = Backbone.Collection.extend({
model: App.Models.Contact,
url: 'contacts',
});
在我看来
App.Views.Contacts = Backbone.View.extend({
tagName: 'tbody',
initialize: function() {
this.listenTo(this.collection, 'sync', this.render);
this.listenTo(this.collection, 'add', this.addOne);
this.collection.fetch({
// update: true,
// remove: false
});
},
render: function() {
// append the list view to the DOM
$('#allcontacts').append(this.el);
// render each of the single views
this.collection.each( this.addOne, this);
return this;
},
addOne: function(contact) {
var contactView = new App.Views.Contact({ model: contact});
this.$el.append(contactView.render().el);
}
});
在我的 app.js 中
// Run App
jQuery(document).ready(function($) {
// Create an Instance of the collection
App.contacts = new App.Collections.Contacts;
// Init BB Router
new App.Router.Route;
Backbone.history.start(); // Kick it all off.
});
【问题讨论】:
-
从上面的代码看不出集合为什么会被调用两次,可以加
App.Collections.Contacts代码吗? -
完成了,但我不这么认为。
标签: javascript backbone.js backbone-views backbone-routing backbone.js-collections