5

在我的基于 Backbone.js 的应用程序中,我正在与我的 API 交谈,该 API 以 204 状态和一个空正文响应,以防请求的集合尚不包含任何数据。在我看来,这就是 RESTful API 在这种情况下应该如何响应。

现在在我的应用程序中,我遇到了问题,显然在收到 204 响应后没有触发任何事件。我试图绑定resetall喜欢:

  FoosCollectionView.prototype.initialize = function() {
    this.collection = new FoosCollection;
    this.collection.bind('reset', this.render, this);
    this.collection.bind('all', this.render, this);
    return this.collection.fetch();
  };

但这些事件永远不会发生。所以我试图给 fetch 一些回调:

  FoosCollectionView.prototype.initialize = function() {
    this.collection = new FoosCollection();
    return this.collection.fetch({
      success: function(a, b, c) {
        debugger;
      },
      error: function(a, b, c) {
        debugger;
      },
      complete: function(a, b) {
        debugger;
      }
    });
  };

相同的行为。如果响应是 204,则不会到达任何调试语句。那么我该如何处理 204 响应呢?我是否必须深入研究sync并在那里为 204 添加额外的处理,或者 Backbone 中是否有一些我根本不知道的东西?

谢谢菲利克斯

4

3 回答 3

0

该解决方案似乎同时非常先进和尴尬:

我只是parse在我的集合中定义该方法,以便它检查传递的响应对象是否为空。只有发生 204 时才会出现这种情况。然后在里面parse我设置this.collection.models = []触发reset事件。集合视图绑定到该事件,运行一个可以查看内部的函数this.collection.models。如果没有给出模型,则可以呈现“无内容”模板而不是标准模板。

如果有人有更好的方法,我会很感激!

于 2012-11-12T11:32:26.673 回答
0

Backbone.js 将此类响应包装到空集合中。我正在使用它作为解决方法。

render: function(){
   if (this.collection.length == 0) {
       console.log('empty response');
       // initialize with default values
       this.collection.reset(data);
   }
   // do usual stuff
}
于 2015-04-22T20:37:17.660 回答
0

今天也出现了同样的问题,从结论上说,我的代码是错误的。修改代码后,success()当服务器响应时调用回调204 No Content

主干:1.2.3
jQuery:2.1.4

错误代码:

FooCollection = Backbone.Collection.extend({
  url: '/foo',

  model: FooModel,

  fetch: function (options) {

    // do something.

    // Actually, you should call `Backbone.Collection.prototype.fetch()`.
    return Backbone.Model.prototype.fetch.call(this, options);
  }
});

所以,如果你遇到这个问题,你应该检查代码中是否有任何错误。无论如何,如果要处理204 No Content响应,则有以下方法。(不建议)

  initialize: function() {
    this.collection = new FooCollection();

    var _this = this;
    this.collection.fetch({
      success: function (collection, response, options) {
      },
      error: function (collection, response, options) {
      }
    }).done(function (data, textStatus, jqXHR) {
      if (jqXHR.status === 204) {
        // do something.
        // e.g. _this.collection.reset();
      }
    });
  }
于 2016-01-08T15:45:39.767 回答