我是 Backbone 新手。我找到了添加 Deferred 的代码,以便我们可以添加 Promise。这是代码
getPatientInfo: function fetch(options) {
var deferred = $.Deferred();
Backbone.Model.prototype.fetch.call(this, _.extend({
deferred: deferred
},
options));
return deferred;
},
调用getItem函数的代码是这样的
this.item.getPatientInfo().done(_.bind(function() {
this.renderPatient(this.item);
},this))
.fail(function(error){
// This won't show unlike native $.ajax .fail where it will show the error
// Not sure why it's not working
console.log(error);
});
但是,当我尝试模拟关闭网络等故障时,.fail 将无法捕获失败的 GET 请求。我不会执行 console.log(error);
但是,如果我使用 native jquery 更改它,例如使用 $.ajax().success().error(function(error){console.log(error)}),则 .error 将起作用,我将能够在我的控制台选项卡中查看错误。
出了什么问题?
更新是为了防止出现问题,但我认为并不理想。因为它丢失而修补它并不是一个好主意
this.item.getPatientInfo().done(_.bind(function() {
if (this.item.attributes.info !== undefined) {
this.renderPatient(this.item);
}
},this))
最佳答案
Backbone 模型已经返回了延迟,我认为这种过于复杂的实现没有充分的理由 - 使用 Backbone 比反对它更好。例如
var SomeModel = Backbone.Model.extend({
url: 'http://jsonplaceholder.typicode.com/posts/1'
});
var someModel = new SomeModel();
someModel.fetch()
.done(function(response) {
console.log('Post title: ', response.title);
console.log('Post body: ', response.body);
})
.fail(function(jqXHR, textStatus, errorThrown) {
console.log('failed');
});
fiddle :http://jsfiddle.net/ferahl/5zzzchpq/
请注意,您还可以访问 done
中的新属性,即 someModel.get('title')
,或者您可以使用 模型在成功和失败时触发的 'sync'
和 'error'
事件。
关于javascript - 当 api 调用超时时,BackboneJS 无法转到 .fail,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32385077/