2012-08-27 59 views
3

通過使用AJAX我可以訪問XHR對象只是簡單地提出:如何訪問XHR對象進行backbone.model保存

$.ajax().fail(function (XHR) { 
    // some code 
}); 

當保存骨幹型號:

var MyView = Backbone.View.extend({ 

    saveModel: function() { 
     this.myModel.save({ 
      error: this.onError 
     }); 
    } 


    onError: function (xhr) { 
     // how to access xhr? 
    } 

}); 

我應該如何獲得XHR當我保存一個backbone.model onError服務器事件?

回答

5

當你調用任何通過Backbone.Sync去的功能,骨幹返回XHR參考:

var MyModel = Backbone.Model.extend({ 
    url: "/some/path/that/is/an/error/" 
}); 

var myModel = new MyModel(); 

xhr = myModel.save({} , { 
    error: function(model, response) { 
     console.log(xhr);    
    } 
}); 

另外,還要注意Model.save()需要兩個參數 - 屬性保存之前有所改變,而且選項散列作爲第二個參數。

這裏有一個例子的jsfiddle:http://jsfiddle.net/edwardmsmith/8AVjy/7/

發表評論:

我從來沒有真正需要做的,但是這是我可能會做的事:

var MyModel = Backbone.Model.extend({ 
    url: "/some/path/that/is/an/error/" 
}); 

var MyView = Backbone.View.extend({ 

    saveModel: function() { 
     that = this; 
     xhr = this.model.save({}, { 
      error: function (model, resp) { 
       that.onError(xhr); 
      } 
     }); 
    }, 

    onError: function (xhr) { 
     // how to access xhr? 
     console.log(xhr);    
    } 

}); 

var myModel = new MyModel(); 

var myView = new MyView({model: myModel}); 

myView.saveModel(); 

更新的jsFiddle爲此:http://jsfiddle.net/edwardmsmith/8AVjy/14/

+0

感謝很好的解釋。 –

+0

hm,model.save對我而言返回undefined ... – wik