How to add a default error handler to all Backbone models?

前端 未结 1 344
离开以前
离开以前 2021-01-02 03:27

Background:

Backbone model provides an option to register a fallback error handler that will be called each time a call to the server fails and no specific handler

1条回答
  •  生来不讨喜
    2021-01-02 03:47

    Backbone uses jQuery's AJAX method calls by default. You can hook in to this directly, instead of using Backbone:

    http://api.jquery.com/ajaxError/

    If that doesn't give you what you want, you can override the "fetch" method in Backbone's model:

    
    var originalFetch = Backbone.Model.prototype.fetch;
    
    Backbone.Model.prototype.fetch = function(options){
    
      var originalError = options.error;
    
      options.error = function(model, error){
        if (originalError){ originalError(model, error); }
    
        // call your global error handler here.
        App.myGlobalErrorHandler(model, error);
    
      }
    
      originalFetch.apply(this, arguments);
    };
    

    0 讨论(0)
提交回复
热议问题