コレクションに を追加しているときに、 と が add イベントをリッスンしているという問題が発生してCollectionA
いCollectionA
ますCollectionB
。ただし、 に追加すると、両方のコレクションに対して追加イベントがトリガーされCollectionA
ます。 CollectionA
およびURLCollectionB
を拡張して設定するだけの基本的なコレクションです。Backbone.Collection
定義を表示
ModelViewA = Backbone.View.extend({
...
render : function() {
var self = this;
var attributes = this.model.toJSON();
this.$el.html(this.template(attributes));
var collectionB = new CollectionB();
var collectionViewB = new CollectionViewB();
collectionB.fetch({
self.$el.append(collectionViewB.render().el);
});
return this;
},
...
});
CollectionViewA = Backbone.View.extend({
initialize : function() {
this.collection.on('add', this.renderOne, this);
},
...
render : function() {
this.collection.forEach(this.renderOne, this);
return this;
},
renderOne : function(model) {
console.log('Added to Collection A');
var view = new ViewA({ model : model });
this.$el.append(view.render().el);
return this;
}
});
CollectionViewB = Backbone.View.extend({
initialize : function() {
this.collection.on('add', this.renderOne, this);
},
...
render : function() {
this.collection.forEach(this.renderOne, this);
return this;
},
renderOne : function(model) {
console.log('Added to Collection B');
var view = new ViewB({ model : model });
this.$el.append(view.render().el);
return this;
}
});
これらのイベントのカスケードを開始する方法は次のとおりです...
var collectionA = new CollectionA();
var modelViewA = new ModelViewA({
model : collectionA.at('some id');
});
$('body').append(modelViewA.render().el);
$('body').empty();
var collectionViewA = new CollectionViewA({ collection: collectionA });
$('body').append(collectionViewA.render().el);
collectionViewA.add([{...}]);
このコードは、modelView を使用して初期ビューを正しく出力します。その後、適切にレンダリングされますがcollectionViewA
、追加イベントをトリガーすると追加が試行されるCollectionA
ためCollectionB
、追加イベントが呼び出されるたびにコンソールに次のように表示されます
Added to Collection B
Added to Collection A
もレンダリングしようとしますCollection B
が、テンプレートにモデルが指定されていないため、エラーがスローされます。
これがあまりにも紛らわしい場合はお知らせください。この説明をもう少し洗い流すことができます。
ありがとう!