Reputation: 240
Is it possible to create a view which lists a collection which is binded to different models? Also can the sort function be used?
For example I have 'sales' and 'accounts' model and would like to make a view with all the names of the people working in those departments.
Thanks
Upvotes: 0
Views: 1394
Reputation: 8581
Sure. What you usually do is end up using a combination of applying event listeners on the collection, creating small subviews which represent each model and binding the model event handlers through that.
BigView = Backbone.View.extend({
el: 'ul', // This view is a <ul> and we'll be adding the model views
initialize: function() {
// This collection represents the collection you passed in
// For our purpose lets say it was a SalesCollection
this.collection.on('reset', this.addAllSales, this);
this.collection.on('add', this.addSale, this);
},
addAllSales: function() {
var that = this;
this.collection.each(function(sale) {
that.addSale(sale);
});
}
addSale: function(model) {
var view = new Subview({
'model': model
});
this.$el.append(view.render().el);
}
});
SaleView = Backbone.View.extend({
initialize: function() {
this.model.on('change', this.something, this);
},
render: function() {
this.$el.html(); // Or whatever else you need to do to represent a sale as view
return this;
}
something: function(model) {
// Code for something
}
});
So in this example, you basically have your main view that has a collection (e.g. sales). When the sales collection is reset, it fires up the addAllSales()
. Each time an sale is added to the collection we add a subview that represents the specific model (sale model). In this subview, we take care of binding events to the model changes which then do something.
Upvotes: 3