我对各个客户模型有一个观点,即客户和客户的集合在建设中。客户模型的要求是有道理的 - 它是客户的观点。收集的要求......我不确定这是否是一种气味,并且会喜欢反馈!
它需要收集的原因是,视图中的按钮可以从customers集合中删除客户,并且视图还可以侦听集合删除事件以查看是否必须取消渲染(已成功从中取消集合)。
var CustomerView = Backbone.View.extend({
events: {
'click button.delete': 'remove'
},
initialize: function() {
_.bindAll(this, 'render', 'unrender', 'remove', 'removed');
this.model.bind('change', this.render);
this.collection.bind('remove', this.removed);
}
// render / unrender removed for brevity
remove: function () {
this.collection.remove(this.model);
},
removed: function (customer) {
if (this.model === customer) {
this.unrender();
}
}
});
以下是视图的创建方式:
var CustomersView = Backbone.View.extend({
initialize: function () {
_.bindAll(this, 'appendCustomer');
this.model.customers.bind('add', this.appendCustomer);
},
appendCustomer: function (customer) {
var customerView = new CustomerView({
model: customer,
collection: this.model.customers
});
$(this.el).append(customerView.render().el);
}
});
我以为我可以在这个appendCustomer方法中以某种方式连接CustomerView,而不是简单地将客户集合交给CustomerView批发。
思考?谢谢!
答案 0 :(得分:8)
如果要通过集合添加这些模型,则可能需要使用模型的集合属性进行调查。这将取代您计划提供的客户关联。
鉴于上述情况,您可能只需要将模型传递到视图中。如果你需要访问模板中的集合或其他,它只是'this.model.collection'。
此外,您可以简单地在模型上调用'destroy'方法,它将从集合中删除。然后,您将使用与现在相同的事件绑定策略,除非使用此内置集合。
答案 1 :(得分:4)
您只需要考虑events
而不是显式方法调用。
在此示例中,我使用自定义事件。
// simplified code
var CustomerView = Backbone.View.extend({
events: {
'click button.delete': 'remove'
},
initialize: function() {
this.model.bind( "app:remove", this.removed );
},
remove: function () {
this.model.trigger( "app:remove" );
},
removed: function (customer) {
this.unrender();
}
});
// The collection it self removes the model
var CustomersCollection = Backbone.Collection.extend({
initialize: function(){
this.on( "app:remove", this.remove )
}
});