当对服务器的 ajax 请求失败时如何使用 defaults 属性

How to use defaults attribute when ajax request to the server is failed

本文关键字:何使用 defaults 属性 失败 请求 服务器 ajax      更新时间:2023-09-26

>我在下面有一个集合

var Collection = Backbone.Collection.extend({
        model: Model,
        url: 'messages',
        defaults :{
            subject: 'this is subject',
            message: 'This is message'
        }
    });

现在我想要的是当 ajax 请求message失败时,我希望我的应用程序使用默认数据,但我当前的应用程序不使用它。

以下是我使用它的方式。

var collection = new Collection();
        collection.fetch().then(function () {
            new SomeView({ collection: collection });
        }, function (status, error) {
            new SomeView({ collection: collection });
        });

我在上面的代码中所做的是,如果获取成功或失败,我仍然调用相同的视图并传递相同的集合。现在,当它失败时,集合应该具有默认内容。但不幸的是,它没有它们。

这样做的主要目的是我希望我的应用程序能够工作,即使没有可用的服务器,也应该能够处理集合中默认属性中存在的静态数据。

如果是,是否有可能,那么我该如何使其工作?

默认值在模型中设置,而不是在集合中设置。如果获取失败,您可以做的是使用默认值向集合添加新模型:

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 });
});

您可以在此小提琴中尝试这两个选项