我正在尝试使用Backbone和Marionette Composite视图,Collection视图和Item视图将表输出到DOM。我的代码是:
var TableDataView = Backbone.Marionette.ItemView.extend({
tagName: "td",
template: "#data-cell-template",
initialize: function(){
console.log('IN TABLEDATA');
console.log('and this.model is ');
console.log(this.model);
}
});
var ScoreRowView = Backbone.Marionette.CompositeView.extend({
tagName: "tr",
childView: TableDataView,
template: "#row-template",
initialize: function(){
console.log('in composite row and this.model is ');
console.log(this.model);
//var tableDataView = TableDataView();
},
});
// The grid view
var TableView = Backbone.Marionette.CollectionView.extend({
tagName: "table",
template: "#table-template",
childView: ScoreRowView,
initialize: function () {
console.log('this.collection is');
console.log(this.collection);
},
});
// ----------------------------------------------------------------
// Below this line is normal stuff... models, templates, data, etc.
// ----------------------------------------------------------------
var countryData = [
{
country: "england",
scores: [14, 56, 88]
},
{
username: "ireland",
scores: [56, 23, 90]
}
];
var Country = Backbone.Model.extend({});
var CountryCollection = Backbone.Collection.extend({
model: Country
});
var countryList = new CountryCollection(countryData);
var tableView = new TableView({
collection: countryList
});
tableView.render();
console.log(tableView.el);
$("#table").html(tableView.el);
表格应如下所示:
请注意,带有数字的单元格有很多自定义css,并且会有点击事件,因此需要在自己的视图中。
但是,使用上面的代码,CompositeView
并未将模型发送到ItemView
。在this小提琴中,只需将ItemView
证明为ItemView
即可到达childView
。我的jsfiddle是here。如何将数据传递到ItemView
?
答案 0 :(得分:0)
您需要添加到ScoreRowView构造函数:
var tdData = [this.model.get('country')].concat(this.model.get('scores')).map(function(item) {
return {
value: item
}
})
this.collection = new Backbone.Collection(tdData);