0

现在我有一个获取值的集合,然后每个附加到重置事件的视图都会再次呈现

问题是我还必须发出另一个查询来获取检索到的记录总数,并且只有在该 ajax 调用完成后才会触发重置事件

用一些代码更清楚:

fetch: function() {
  options = { data: this.getParams() };
  this.fetch_total();
  return Backbone.Collection.prototype.fetch.call(this, options);
},

fetch_total: function() {
  var that = this;
  var options = { 
    url: this.url + '/count',
    data: this.getParams(),
    contentType: 'application/json',
    success: function(resp, status, xhr) {
      that.total = parseInt(resp);
      return true;
    }
  };
  return $.ajax(options);
}

如您所见,我必须向 localhost/myentity/count 发出 get 以获取实体的数量...

问题是我需要在刷新视图之前更新 collection.total 变量,这意味着我需要在刷新所有视图之前完成对 localhost/myentity 和 localhost/myentity/count 的 GET 请求……

知道如何实现吗???

4

3 回答 3

2

如果您选择的 $ 是 jQuery>1.5,您可以利用延迟对象在两个调用都完成时手动触发重置事件。与您的答案类似,但更具可读性且无需链接调用:

fetch: function() {
  options = {silent: true, data: this.getParams()};
  var _this = this;
  var dfd_total = this.fetch_total();
  var dfd_fetch = Backbone.Collection.prototype.fetch.call(this, options);

  return  $.when(dfd_total, dfd_fetch).then(function() {
        _this.trigger('reset', _this);
  })
},

fetch_total: function() {
    // what you have in your question
}

还有一个模拟这些调用的小提琴http://jsfiddle.net/rkzLn/

当然,一次性返回结果和总数可能更有效,但我想这不是一个选择。

于 2012-08-14T06:56:54.113 回答
1

我认为@nikoshr 的答案是一个很好的答案,这样您就不必修改您的 API。如果您认为要减少对服务器的调用,请考虑从具有分页信息的端点返回一个对象。

{
  count: 1243,
  page: 3,
  per_page: 10,
  results: [
    ...
  ]
}

然后覆盖集合的解析功能

parse: function(res) {
  this.count = res.count;
  this.page = res.page;
  this.per_page = res.per_page;
  // return the collection
  return res.results;
}

资源

于 2012-08-14T16:03:58.027 回答
0

我想我找到了一种方法。我所做的是静默触发 fetch 调用,而不触发“重置”事件

在那里,从回调中,我发出总数的获取(GET 到 localhost/myentity/count)

从总回调中,我终于触发了重置事件

在代码中是这样的:

fetch: function() {
  var that = this;
  options = {
    // will manually trigger reset event after fetching the total
    silent: true,       
    data: this.getParams(),
    success: function(collection, resp) {
      that.fetch_total();
    } 
  };
  return Backbone.Collection.prototype.fetch.call(this, options);
},

fetch_total: function() {
  var that = this;
  var options = { 
    url: this.url + '/count',
    data: this.getParams(),
    contentType: 'application/json',
    success: function(resp, status, xhr) {
      that.total = parseInt(resp);
      // manually trigger reset after fetching total
      that.trigger('reset', that);    
      return true;
    }
  };
  return $.ajax(options);
}

这是我的第一次尝试,我想知道是否有更简单的方法

于 2012-08-14T06:32:30.763 回答