我在使用 Backbone 中的单个集合渲染 2 个视图时遇到问题。在我的应用程序中,有一个主视图,我正在其中初始化项目集合,因此所有子视图都可以访问它。有一个项目视图,用于在将任何项目添加到集合时在两个视图(快速和正常)中呈现单个项目。必须为应用程序的所有路由呈现快速视图。然而,普通视图将仅呈现调用的域/结帐路由。可以通过 2 种方式调用域/结帐:
- 单击结帐按钮 - 在这种情况下,两者都同步并且工作正常。
- 直接访问域/结帐路径——在这种情况下,快速和普通视图不同步。
// 主视图
var mainView = Backbone.View.extend({
el: 'body',
template: {
header: Handlebars.compile(headerTemplate),
mainNav: Handlebars.compile(mainNavtemplate),
footer: Handlebars.compile(footerTemplate)
},
initialize: function() {
_.bindAll(this);
AW.collection.bag = new bagCollection();
AW.collection.bag.fetch({reset:true});
},
render: function() {
this.$el.html(this.template());
this.loadSubView('bagQV');
}
});
// 快速浏览
var bagQuickView = Backbone.View.extend({
tagName: 'div',
id: 'myBagQV',
template: Handlebars.compile(bagQuickViewTemplate),
initialize: function() {
_.bindAll(this);
//this.collection.fetch({reset:true});
//this.collection.bind("reset", _.bind(this.render, this));
this.listenTo(this.collection, 'add', this.addItem);
this.listenTo(this.collection, 'reset', this.render);
},
render: function() {
if($('#myBagQV').length == 0) {
this.$el.html(this.template());
$('body').append(this.el);
}
this.addAllItems();
return this;
}
});
// 普通视图
var bagView = Backbone.View.extend({
tagName: 'div',
id: 'myBag',
template: Handlebars.compile(checkoutBagTemplate),
initialize: function() {
_.bindAll(this);
//this.collection.fetch({reset:true});
//this.collection.bind("reset", _.bind(this.render, this));
this.listenTo(this.collection, 'add', this.addItem);
this.listenTo(this.collection, 'reset', this.render);
},
render: function() {
this.$el.html(this.template());
$('#checkoutContainer #details').append(this.el);
this.addAllItems();
return this;
}
});