如何在Backbone模型获取调用期间触发错误?

Ale*_* N. 1 error-handling backbone.js

在Backbone的获取过程中触发错误回调的正确方法是什么?例如,我的代码如下:

this.model.fetch({
  success: function(model, response, options){
    console.log('data loaded');
  },
  error: function(model, response, options){
    console.log('error loading data');
  }
});
Run Code Online (Sandbox Code Playgroud)

在模型中,我有一个类似于此的解析函数:

parse: function(response, options){
    var data = response.modeldata);
    if(data.inaccessible == true) {
       //trigger error
    } else return data;
},
Run Code Online (Sandbox Code Playgroud)

我需要在条件块内放置什么才能触发错误回调?

Bar*_*cha 5

如果要执行附加到error选项的回调,则需要修改模型的解析函数,如下所示.

parse: function(response, options) {
    var data = response.modeldata;
    var error = options.error;

    if (data.inaccessible === true) {
        if ( error ) error( this, response, options );
    } else {
        return data;
    }
}
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助.