tl;博士 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/