【问题标题】:BackgridJs - How to show an object in gridBackgridJs - 如何在网格中显示对象
【发布时间】:2014-10-02 23:32:40
【问题描述】:

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

{
    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();

标签显示为 [object Object]、[object Object] 和国家根本没有显示。

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

【问题讨论】:

    标签: backbone.js backgrid


    【解决方案1】:

    Backgrid 旨在为Collections 创建表,其中Models 的数据为1 级深度,但您的Model 的数据为2 级深度。您可以选择使用自定义格式化程序,或覆盖 ColumnCells 的 render 方法,但可能最简单的解决方案只是将模型“扁平化”一点让 Backgrid 更容易消化。

    例如:

    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);
        }
    });
    

    然后将类似的 flatten 方法添加到您的 Collection:

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

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

    var grid = new Backgrid.Grid({
        ...
        collection: articles.flatten()
    });
    

    希望对您有所帮助。

    【讨论】:

      猜你喜欢
      • 2011-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多