创建具有 Marionette 视图的 HTML table

Creating a HTML table with Marionette views

我正在尝试使用 Backbone 和 Marionette 复合视图、集合视图和项目视图将 table 输出到 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);

table 应该是这样的:

请注意带有数字的单元格有很多自定义 css 并且会有点击事件,因此这些需要在它们自己的视图中。

但是,使用上面的代码,CompositeView 没有将模型发送到 ItemView。在this fiddle, it does reach the ItemView simply by proving the ItemView as a childView. My jsfiddle is here。如何将数据传递给 ItemView?

您需要添加到 ScoreRowView 构造函数:

var tdData = [this.model.get('country')].concat(this.model.get('scores')).map(function(item) {
                return {
                    value: item
                }
             })
this.collection = new Backbone.Collection(tdData); 

http://jsfiddle.net/sergeir82/t53t5x78/