Alex N.
Alex N.

Reputation: 15935

How to trigger an error during Backbone model fetch call?

What is the right way to trigger error callback in Backbone's fetch process? For example, I have code as follows:

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

In the model I have a parse function akin to this:

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

What do I need to put inside the conditional block to trigger the error callback?

Upvotes: 1

Views: 478

Answers (1)

Bart Jedrocha
Bart Jedrocha

Reputation: 11570

If you want to execute the callback attached to the error option, you'll need to modify your model's parse function as follows.

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;
    }
}

Hope this helps.

Upvotes: 5

Related Questions