BackgridJs - 如何在网格中显示对象

时间:2014-10-02 23:32:40

标签: backbone.js backgrid

我想为此文档(模型)显示一个网格:

{
    id: "53f7ba4b30d2317912fc8004",
    title: "Hellow world",
    on_slideshow: false,
    country: {
        name: "United state",
        country_code: "US"
    }
    tags: [
        {
            name: "backbonejs"
            object_id: "72691"
        },
        {
            name: "backgrid"
            object_id: "72692"
        }
    ]
}

在我的js文件中..

var grid = new Backgrid.Grid({
    columns: [{
        name: "title",
        label: "Title",
        cell: "string"
    },
    {
        name: "country",
        label: "Country",
        cell: "string"
    },
    {
        name: "on_slideshow",
        label: "Slide",
        cell: "boolean"
    },
    {
        name: "tags",
        label: "Tags",
        cell: "string"
    },
    {
        name: "pub_date",
        label: "Publiched",
        cell: "string"
    }],
  collection: articles
}).render();

标签显示为[对象对象],[对象对象],国家/地区根本没有显示。

如何正确显示标签的名称和国家/地区列表?

1 个答案:

答案 0 :(得分:0)

Backgrid旨在为Collection s创建表格,其中Model的数据深度为1级,但您的Model数据深度为两级。您可以选择使用自定义格式化程序,或覆盖render Column的{​​{1}}方法,但最简单的解决方案可能就是到"展平"你的模型有点让Backgrid很容易消化。

例如:

Cell

然后在var Article = Backbone.Model.extend({ flatten: function() { var flatVersion = this.toJSON(); flatVersion.country = this.get('country').name; flatVersion.tags = this.get('tags').join(', '); return new Backbone.Model(flatVersion); } });

中添加类似的展平方法
Collection

然后最终将扁平版本传递给Backgrid:

var Articles = Backbone.Collection.extend({
    flatten: function() {
        return this.invoke('flatten');
    }
});

希望有所帮助。

相关问题