使用Marionette视图创建HTML表

时间:2015-08-07 11:02:04

标签: javascript backbone.js marionette

我正在尝试使用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);

表格应如下所示:

enter image description here

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

但是,使用上面的代码,CompositeView并未将模型发送到ItemView。在this小提琴中,只需将ItemView证明为ItemView即可到达childView。我的jsfiddle是here。如何将数据传递到ItemView

1 个答案:

答案 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); 

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