如何在重写Backbone'时触发错误?方法

How to fire an error when overriding Backbone's the "parse" method

本文关键字:错误 方法 重写 Backbone      更新时间:2023-09-26

当我在parse()方法中收到的服务器响应无效时,我试图抛出一个错误。

我尝试将选项参数中的error键设置为false或在我的模型的覆盖parse()方法中调用options.xhr.error(this, resp, options);方法,但它们都没有导致fetch()方法的error回调触发。

什么线索吗?

下面是实际的例子:

Backbone.Model.extend({
  parse: function parse(resp, options){
    if(resp && resp.meta.success){
      return resp.response;
    }else{
      //Throw an error which cause the "error" callback of the fetch method to get triggered
    }
  }
an});

如果响应有错误,您应该能够重写同步函数以触发错误回调,或者使用主响应调用默认的成功处理程序:

var MyModel = Backbone.Model.extend({
  sync: function(method, model, options){
    var error = options.error;
    var success = options.success;
    options.success = function(resp){
      if (resp && resp.meta.success){
        success(resp.response);
      } else{
        error(resp.response);
      }
    };
    return MyModel.__super__.sync.call(this, method, model, options);
  }
});