当 api 调用超时时,BackboneJS 无法转到 .fail
BackboneJS fails to go to .fail when api call times out
我是 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);
但是如果我使用原生 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 模型已经 returns 延期了,我认为这种过于复杂的实现没有充分的理由 - 使用 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'
事件代替那些延迟回调触发成功和失败。
我是 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);
但是如果我使用原生 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 模型已经 returns 延期了,我认为这种过于复杂的实现没有充分的理由 - 使用 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'
事件代替那些延迟回调触发成功和失败。