Backgrid懒洋洋地加载一列

时间:2015-11-12 14:41:12

标签: asynchronous backbone.js collections backgrid

我正在使用Backgrid创建一个表。为此,我有

Entities.RecipeCollection = Backbone.PageableCollection.extend({
model: Entities.Recipe,
url: '/api/v1/recipes',
state: {
  firstPage: 1
},
queryParams: {
  sort_by : 'id',
  currentPage: 'page',
  pageSize: 'per_page'
},
parseState: function (resp, queryParams, state, options) {
  return {totalRecords: resp.meta.total}
},
parseRecords: function (response, options) {
  return response.results
}

})

然后在我的控制器中我有

List.Controller = {
   listRecipes: function () {

   $.when(recipeRequest).done(function (recipes) {
     var recipesListView = new List.Pagination({
       collection: recipes
    })

    var columns = [{
      name: id,
      cell: 'String'
    // column 1
   }, {
     // column 2
   }, {
     // column 3 is not available and can only be retrieved by a second
     // call to the server using a different endpoint and with the id from column 1
   }]

   var grid = new Backgrid.Grid({
    columns: columns
    collection: recipes
   })

recipesListLayout.on('show' function () {
    recipesListLayout.show(grid)
   }
  }
}

所以我陷入困境的是试图弄清楚如何更新Backgrid的集合。我想做像

这样的事情
  1. 一旦Backgrid加载循环遍历集合中的每个项目
    1. 使用id
    2. 发出获取第三列详细信息的请求
    3. 在每次从服务器返回时,使用返回的数据更新该行和第3列。
  2. 如果你能指出我可以采取的方法,我会非常感激。我见过的大多数方法都建议在加载网格之前进行第二次调用,但是我希望用户能够看到网格,即使所有字段都不可用。

1 个答案:

答案 0 :(得分:1)

您可以创建这样的自定义单元格,并在定义列

时使用自定义单元格
List.Controller = {
   listRecipes: function () {

   $.when(recipeRequest).done(function (recipes) {
     var recipesListView = new List.Pagination({
       collection: recipes
   })

    Backgrid.CustomCell= Backgrid.Cell.extend({
            className: 'custom-cell',
            events: {
                'click .some_class': 'doSomething'
            },
            doSomething: function (event) {
            },
            render: function () {
                var html = "";
                // make the ajax call with the id from 1st column
                // you can get the id from this.model.get("id")
                $.ajax({
                    url: "someurl"
                })
                  .done(function( data ) {
                    //do something with data
                    // for example 
                    html = "<p class='sth'>" + data.name + "</p>";
                }).always(function(){
                     this.$el.html(html);
                     this.delegateEvents();
               });
               return this;
            }
        });
    }

   var columns = [{
      name: id,
      cell: 'String'
        // column 1
   }, {
      // column 2
   }, {
       // and use the custom cell like this
       name: "",
       label: "Custom data from 2nd call",
       editable: false,
       cell: "custom"
  }]

   var grid = new Backgrid.Grid({
     columns: columns
     collection: recipes
   })

   recipesListLayout.on('show' function () {
      recipesListLayout.show(grid)
   }
 }

}