2014-09-26 58 views
0

我用骨幹庫骨幹錯誤處理

服務器需要爲每個請求的授權

因此,任何請求,可以返回401錯誤

服務器如何fetch()後處理401錯誤調用在型號和召回fetch()具有相同的選項?

我使用錯誤處理的型號:

var Stores = Backbone.Collection.extend({ 
initialize: function(models, options) { 
    var self = this; 
    this.options = options; 
    this.on({ 
     'error': function(model, xhr, options) { 
      if (xhr.status == 401) { // Not authorized 
       API.restoreToken(function() { 
        self.fetch(options); 
       }); 
      } 
     } 
    }); 
} 
}); 

但問題是:當我打電話self.fetch(options);,對象options已結束success功能。 所以,self.fetch(options);不叫原來success函數

回答

0

使用self.fetch(self.options);

+0

'self.options' - 是模型對象的成員,它被傳遞而創建的模型對象的 – belykh 2014-09-26 11:26:01

2

服務器需要爲每個請求

這看起來像一個全球性的東西,所以使用$.ajaxPrefilter()配不配得很好的授權。從 here

描述引用:處理定製的Ajax選項或發送的每個請求之前修改現有的選項,並且它們通過$.ajax()處理之前。

例如重塑每AJAX請求的誤差函數

$.ajaxPrefilter(function(options, originalOptions, jqXHR) { 
    // Save original function 
    var originalError = options.error 
    // Let's hack 
    options.error = function(ejqXHR, textStatus, errorThrown){ 
    if(ejqXHR.status == 401) { 
     API.restoreToken(function() { 
     //Do magic, probably reAjax with options 
     //Probably add anti-infinite-ajax mechanism 
     }); 
    }else{ 
     //If not 401 handle it originally 
     originalError(ejqXHR, textStatus, errorThrown) 
    }  
    } 
}