0

I want to show a grid for this document (model):

{
    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"
        }
    ]
}

in my js file ..

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

Tags show as [object Object],[object Object] and country didn't show at all.

How can I show them properly, Tags' name and country list ?

elhoucine
  • 2,356
  • 4
  • 21
  • 37

1 Answers1

0

Backgrid is designed to create tables for Collections with Models whose data is 1-level deep, but your Model has data two-levels deep. You could opt to use custom formatters, or override the render method of your Column's Cells, but probably the simplest solution is just to "flatten" your model a bit to make it easy for Backgrid to digest.

For example:

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

and then add a similar flatten method to your Collection:

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

and then finally pass the flattened version to Backgrid:

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

Hope that helps.

machineghost
  • 33,529
  • 30
  • 159
  • 234