Search code examples
backbone.jsmarionettebackgrid

Backgrid doesn't render the grid with the updated collection


I'm using Backgrid and I create the Backgrid Object as follows in my Controller:

  $.when(recipeRequest).done(function (recipes) {
     List.grid = new Backgrid.Grid({
      columns: columns, // where columns is defined elsewhere
      collection: recipes // recipes is the result of a fetch
    })

  // Then add it to the Marionette template
}

The above works perfectly and items display as expected

Once the table is displayed we are providing filtering functionality ServerSide as follows:

  filterRecipes: function (query) {
  // remove any incomplete network requests
    _.each(RecipeManager.fetchXhrs, function (r) {
        r.abort()
     })
  // get a filtered set of recipes
  var filteredRecipes = RecipeManager.request('recipe:entities', query)
  $.when(filteredRecipes).done(function (recipes) {

     // this line shows that the result set is being updated as expected with for example 6 results
    console.log(recipes)

    // setting the new recipe result set to the grid.collection 
    List.grid.collection = recipes 

    // here the table rerenders but there are a LOT more results on the table - not 6 as expected
    List.grid.render()  
  })
}

I'm expecting the table to be repopulated with the new collection once the results are returned but my table still shows all the old records.

I'm following the example written here How would I refresh a Backgrid table with new data? So it should redraw the table once the collection has been reset? Or do I need to empty the table first? Any ideas where I might be going wrong?


Solution

  • From backgridjs

    Fully reactive. Relevant parts of the grid re-renders automatically upon data changes.

    I have not gone through annotated source code but am guessing rerendering is tied to collection events. So, you do not need to explicitly call the render method.

     $.when(filteredRecipes).done(function (recipes) {
    
         // this line shows that the result set is being updated as expected with for example 6 results
         console.log(recipes)
    
         // setting the new recipe result set to the grid.collection 
         // considering recipes is backbone collection
         // if result is array of objects then List.grid.collection.reset(recipes)
         // it should re render the grid 
         List.grid.collection.reset(recipes.models); 
     })