Javascript 当对服务器的ajax请求失败时如何使用defaults属性
我下面有一个收藏Javascript 当对服务器的ajax请求失败时如何使用defaults属性,javascript,jquery,backbone.js,Javascript,Jquery,Backbone.js,我下面有一个收藏 var Collection = Backbone.Collection.extend({ model: Model, url: 'messages', defaults :{ subject: 'this is subject', message: 'This is message' } }); 现在我想要的是,当对消息的ajax请求失败时,我希望我的应用
var Collection = Backbone.Collection.extend({
model: Model,
url: 'messages',
defaults :{
subject: 'this is subject',
message: 'This is message'
}
});
现在我想要的是,当对消息的ajax请求失败时,我希望我的应用程序使用默认数据,但我当前的应用程序不使用默认数据
下面是我使用它的方式
var collection = new Collection();
collection.fetch().then(function () {
new SomeView({ collection: collection });
}, function (status, error) {
new SomeView({ collection: collection });
});
我在上面的代码中所做的是,如果fetch成功或失败,我仍然调用相同的视图并传递相同的集合。现在,当它失败时,集合应该具有默认内容。
但不幸的是,它没有这些
这样做的主要目的是希望我的应用程序能够工作,即使没有可用的服务器,也应该能够处理集合中默认属性中存在的静态数据
如果可以,那么如何使其工作?默认值在模型中设置,而不是在集合中设置。如果提取失败,可以使用默认值向集合添加新模型:
var Model = Backbone.Model.extend({
defaults :{
subject: 'this is subject',
message: 'This is message'
}
});
var Collection = Backbone.Collection.extend({
model: Model,
url: 'FakeUrl/messages'
});
var collection = new Collection();
collection.fetch().then(function () {
new SomeView({ collection: collection });
}, function (status, error) {
//adds new model with default values, same as collection.add(new Model());
collection.add({});
console.log(collection.toJSON());
new SomeView({ collection: collection });
});
另一个选项是最初创建包含具有默认值的单个模型的集合。然后在从服务器获取数据时传递{reset:true}。如果获取成功,将删除默认模型,但如果获取失败,则集合仍将包含该模型:
var collection2 = new Collection(new Model());
collection2.fetch({reset: true}).then(function () {
new SomeView({ collection: collection });
}, function (status, error) {
console.log(collection2.toJSON());
new SomeView({ collection: collection });
});
您可以在中尝试这两个选项。在第一个解决方案中,您添加的是空模型,而不是添加具有默认值的新模型。@2619允许您传递原始属性并将其作为模型进行激活。如果您尝试使用小提琴,您将在控制台中看到集合中有一个具有默认属性的项。