让我所有的主干模型在取回失败时做出相同的反应

Let all my Backbone models react the same when fetch fails

本文关键字:失败 模型      更新时间:2023-09-26

我锁定的方式,其中我所有的集合和模型使用相同的逻辑来显示错误时,获取或保存失败。但我不想再写一遍onError回调。我们的目标是让一个方法在失败时根据响应的http错误代码打开错误对话框。

另一种方法是创建一个基本模型和集合,并让你的模型和集合扩展它们,而不是Backbone的:

var BaseModel = Backbone.Model.extend({
  onSyncError: function(model, response) {
    // your error-handling code
  },
  onSyncSuccess: function(model, response) {
    // do stuff if successful
  },
  // Backbone will call your 'sync' if it exists
  sync: function(method, model, options) {
    options.error = this.onSyncError;
    options.success = this.onSyncSuccess;
    Backbone.sync.call(this, method, model, options);
  }
});

然后在你的模型中:

var MyModel = BaseModel.extend({
  // model stuff
});

考虑后,我想到了这样一个解决方案:

function callback(success){
    this.success = sucess;
}
callback.prototyp.error = function(model, response){
    // central error handling here
}
myModel.save(new callback(myModel.success))