異なるモデルにバインドされたコレクションを一覧表示するビューを作成することはできますか? また、ソート機能は使えますか?
たとえば、'sales' および 'accounts' モデルがあり、これらの部門で働くすべての人の名前を含むビューを作成したいと考えています。
ありがとう
異なるモデルにバインドされたコレクションを一覧表示するビューを作成することはできますか? また、ソート機能は使えますか?
たとえば、'sales' および 'accounts' モデルがあり、これらの部門で働くすべての人の名前を含むビューを作成したいと考えています。
ありがとう
もちろん。通常は、コレクションにイベントリスナーを適用し、各モデルを表す小さなサブビューを作成し、それを介してモデルイベントハンドラーをバインドすることを組み合わせて使用します。
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
}
});
したがって、この例では、基本的に、コレクション(販売など)を持つメインビューがあります。セールスコレクションがリセットされると、が起動しaddAllSales()
ます。コレクションにセールが追加されるたびに、特定のモデル(セールモデル)を表すサブビューが追加されます。このサブビューでは、イベントをモデルの変更にバインドし、それが何かを実行します。