undefined corvus
undefined corvus

Reputation: 83

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

I have a collection below

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

Now what I want is when the ajax request to message is failed the I want to my app to use defaults data but my current app does not use that.

Below is the way I am using it.

var collection = new Collection();

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

What I am doing in above code is if fetch is successful or failed still I am calling the same view and passing the same collection. Now when it is failed then collection should have defaults contents. But it does not have them unfortunately.

The main purpose of doing this way is I want my application to work even if there is not server available should be able to work with static data present in default attribute in collection.

Is it possible if yes then how can I make it work?

Upvotes: 2

Views: 54

Answers (1)

Daniel J.G.
Daniel J.G.

Reputation: 35032

The defaults are set in the model instead of the collection. What you can do in case the fetch fail is to add a new model to the collection with the default values:

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

Another option is to initially create the collection containing a single model with the default values. Then pass {reset:true} when fetching the data from the server. If fetch succeeds the default model will be removed, but if it fails the collection will still contain it:

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

You can try both options in this fiddle

Upvotes: 3

Related Questions