如果server / json返回特定的STATUS(例如没有结果),我希望我的集合失败。
问题:未调用默认的错误处理程序(导致集合成功获取json。所以我的想法是使用parse函数在json中查找错误代码。< / p>
但是如何触发错误方法并通知我的视图(并停止尝试创建模型的集合)
/*global define*/
define([
'underscore',
'backbone',
'models/mymodel'
], function (_, Backbone, MyModel) {
'use strict';
var SomeCollection = Backbone.Collection.extend({
model: MyModel,
value: null,
url: function() {
return url: "data/list.json";
},
initialize: function(models, options) {
this.zipcode = options.zipcode;
},
parse: function(response, xhr) {
if(response.status == "OK") {
console.info("Status: "+response.status);
return response.results;
} else {
console.warn("Status: "+response.status+" – Message: "+response.message);
this.trigger('fail') // does not work
return response;
}
}
});
return SomeCollection;
});
答案 0 :(得分:0)
我的博客上有关于此类事情的帖子,不幸的是它是葡萄牙语,但也许谷歌翻译可以帮助你。
http://www.rcarvalhojs.com/dicas/de/backbone/2014/06/24/gerenciando-o-estado-da-aplicacao.html
我喜欢以这种方式处理这个问题
GetSomething:->
@result = @fetch(
success:()=>
@trigger "succesthing1" if @result .status is 204
@trigger "successThing2" if @result .status is 200
error:()=>
@trigger "errorThing" if @result .status is 401
)
现在我可以在视图中侦听这些触发器,并针对特定服务器的结果采取正确的操作
答案 1 :(得分:0)
根据请求返回的承诺,发送事件目前订阅 Backbone sync ,请参阅下面的示例:
(function(Backbone) {
var methods, _sync;
_sync = Backbone.sync;
methods = {
beforeSend: function() {
return this.trigger("sync:start", this);
},
error: function() {
return this.trigger("sync:error", this);
},
complete: function() {
return this.trigger("sync:stop", this);
}
};
Backbone.sync = function(method, entity, options) {
var sync;
if (options == null) {
options = {};
}
_.defaults(options, {
beforeSend: _.bind(methods.beforeSend, entity),
error: _.bind(methods.error, entity)
complete: _.bind(methods.complete, entity)
});
sync = _sync(method, entity, options);
if (!entity._fetch && method === "read") {
return entity._fetch = sync;
}
};
})(Backbone);
希望这有帮助。