Search code examples
marionettebackbone-viewsbackgrid

Dynamically adding columns to BackGrid inside a Marionette view


So, I have a complicated Marionette app with several composite views. I am attempting to add a dynamic BackGrid to the view, but can't seem to get it to add columns. I create the grid and add it to the view as per this post: Backgrid integration. However, it appears that I need to recreate the Backgrid every time I add a column. This is incredibly wasteful!

Any ideas on where to look for a solution?


Solution

  • I was looking for this exact thing as well.

    I found that there was a insertColumn and removeColumn method available on the grid itself. The insertColumn function takes a column formatted in the usual way (the way all the examples are showing) -

    {name:<name_here>, label:<label_here>, cell:<cell_type_here>}

    Adding a column becomes as simple as -

        var Model = Backbone.Model.extend({});
        var Collection = Backbone.Collection.extend({ model: Model });
        var column = {name:"test_name", label:"test_label", cell:"string"};
        var myBackgridObject = new Backgrid.Grid({columns: {}, collection: new Collection([])});
    
        myBackgridObject.insertColumn(column);
    

    This link to the marionette docs might help you as well, it goes over manipulating the grid -

    Backgrid ref - manipulating the grid