我对各个客户模型有一个看法,即客户和客户的集合在建设中.客户模型的要求是有道理的 - 它是客户的观点.收集的要求......我不确定这是否是一种气味,并且会喜欢反馈!
它需要收集的原因是,视图中的按钮可以从customer集合中删除客户,并且视图还可以侦听集合删除事件以查看是否必须取消渲染(已成功从集合中删除) .
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();
}
}
});
Run Code Online (Sandbox Code Playgroud)
以下是创建视图的方式:
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);
}
});
Run Code Online (Sandbox Code Playgroud)
我以为我可以在这个appendCustomer方法中以某种方式连接CustomerView,而不是简单地将客户集合交给CustomerView批发.
思考?谢谢!
如果要通过集合添加这些模型,则可能需要使用模型的集合属性进行调查.这将取代您计划提供的客户关联.
鉴于上述情况,您可能只需要将模型传递到视图中.如果你需要访问模板中的集合或其他,它只是'this.model.collection'.
此外,您可以简单地在模型上调用'destroy'方法,它将从集合中删除.然后,您将使用与此相同的事件绑定策略,除非使用此内置集合.