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 Link Again http://jsfiddle.net/fRTBU/2/
答案 0 :(得分:2)
好的,这里有一些问题。您的事件未在TableView
中触发的原因是,当您使用window.teams
替换其集合时,您会将事件绑定到this.collection = new Backbone.Collection(_.toArray(grid));
集合 - 此时它的集合为no更长window.teams
。
另一个问题是,您尝试将数据显示为如下所示:
Leagues
|______League
| |______Team
| |______Team
|
|______League
|______Team
|______Team
|______Team
...但您的数据结构如下:
Teams
|______Team
|______Team
|______Team
一种解决方案是让TeamCollection
以{ League : "AL", City : "Boston" , TeamId : 1 }
格式接受您的数据,并将更改事件绑定到每个联盟更新LeagueTeamsCollection
的函数,并使用该集合作为2个视图类的基础:CompositeView
和ItemView
。