简体   繁体   中英

Backbone.js 'error' event: how do I know which method (fetch, save, delete) triggered it?

Backbone sync triggers an error event on the model/collection whenever the response is not a 200 status code. In order to implement a default error handling mechanism, I am listening for the error event in my views. This works, but I want to be able to distinguish between errors saving ( save ), deleting ( delete ), and retrieving ( fetch ).

So, in a nutshell, this is sort of what I want:

var MyView = Backbone.View.extend({
  initialize: function(options){
    this.listenTo(this.model, 'error', this.errorHandler);
  },
  errorHandler: function(model, xhr, options){
    // logic would depend on whether the event was triggered by fetch, 
    // save, or delete
    // How can I tell how the event was triggered? 
  }  
});

Does Backbone provide me a way to do that? Does the jqXHR object? Looking for options here.

I know that I could (and some would say, should) use the error callback in options to fetch, etc. but I don't want to have to modify a lot of existing code to create the default behavior.

Do I need to override fetch, save, and delete in a base model to namespace the event or is there something already built in?

Thanks

The callback for Backbones error-event has 3 parameters: model, xhr and options (in that order).

The options object refers to the options that were used to triggered the (failed request. So with in it, you should be able to see what HTTP method was used (I think ti's called "type"?), the statusCode and even the URL it was trying to send the request to.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM