tl;dr http://jsfiddle.net/fRTBU/2/
野球都市のリストを表示しているマリオネットアプリを用意してください。
window.teams = new MyApp.Models.TeamCollection([
{ League : "AL", City : "Boston" , TeamId : 1 },
{ League : "AL", City : "Chicago" , TeamId : 2 },
{ League : "NL", City : "Chicago" , TeamId : 3 }
]);
リーグごとに分類された都市のリストが必要です。
何かのようなもの :
<table>
<tr>
<td>
<h2>AL</h2>
<ul>
<li>Boston 1 </li>
<li>Chicago 2</li>
</ul>
</td>
</tr>
<tr>
<td>
<h2>NL</h2>
<ul>
<li>Chicago 3 </li>
</ul>
</td>
</tr>
</table>
私はそれをレンダリングすることができます。
しかし、新しいチームを追加しようとすると (拡張用:P)
window.teams.push(new MyApp.Models.Team({ League : "NL",
City : "Washington",
TeamId : 4 }));
コレクション変更イベントが発生しない ( JSFiddle 内)
collectionEvents: {
"reset": "myFunc" ,
"change" : "myFunc",
"add" : "myFunc"
},
myFunc: function () {
Logger('myFunc');
var grid = window.teams.groupBy(function (row) {
return row.get("League");
});
this.collection = new Backbone.Collection(_.toArray(grid));
}
または私のアプリで(それを取り巻くより多くのロジックがあります)
ReferenceError: TeamId is not defined
アプリのメイン構造
MyApp.Models.Team = Backbone.Model.extend({
idAttribute: 'TeamId'
});
MyApp.Models.TeamCollection = Backbone.Collection.extend({
model: MyApp.Models.Team
});
MyApp.Views.ListItemView = Backbone.Marionette.ItemView.extend({
tagName: 'tr',
template : '#row-template'
});
MyApp.Views.ListCompositeView = Backbone.Marionette.CompositeView.extend({
itemView: MyApp.Views.ListItemView,
template: "#list-template",
itemViewContainer: "ul",
initialize: function () {
this.collection = new Backbone.Collection(
_.toArray(this.model.attributes));
},
onRender: function () {
$(this.$el).find("h2.ListHead")
.html(this.collection.models[0].get('League'));
}
});
MyApp.Views.TableView = Backbone.Marionette.CompositeView.extend({
itemView: MyApp.Views.ListCompositeView,
tagName: "table",
itemViewContainer: "tbody",
template: "#table-template",
initialize : function () {
this.myFunc();
},
collectionEvents: {
"reset": "myFunc" ,
"change" : "myFunc",
"add" : "myFunc"
},
myFunc: function () {
Logger('myFunc');
var grid = window.teams.groupBy(function (row) {
return row.get("League");
});
this.collection = new Backbone.Collection(_.toArray(grid));
}
});
MyApp.Views.ListItemView
それらが逆に起こっていると私が言うと、コレクションをMyApp.Views.ListCompositeView
取得してモデルを取得するように見えます。
JsFiddle リンクの再 http://jsfiddle.net/fRTBU/2/