recallfx
recallfx

Reputation: 146

Backbonejs collection.fetch() enforce default model parameters

After upgrading Backbonejs to 1.0, fetching collection from server enforces default properties that are not in response.

To be more specific I have created this test that can be verified in jsfiddle.

Suppose we have a backbone model definition with default properties. Property text can be received from server in JSON [{ "text": "updated", "id" : 1}], and property selected is maintained in client side.

var Model = Backbone.Model.extend({
    defaults: function () {
        return {
            text: 'default',
            selected: false
        };
    }    
});

If we use this setup and fetch data from server it will work correctly. Now suppose we add this model in backbone collection like this:

var Models = Backbone.Collection.extend({
    url: '/json/',
    model: Model
});

Create a new collection instance and populate with fetch:

var models = new Models();
models.fetch({
    update : true
});

After that, we take one model in the collection and change selected property to true:

var model = models.get(1);
model.set('selected', true);

Now if we call fetch the collection for the second time, backbone will clear our previously changed property to the default value false even if there was no such value in the response:

models.fetch({
    update : true
});
model = models.get(1);

Getting selected value will return false instead of our previously set true.

model.get('selected');

Workaround: comment out those properties, that are not received from server.

But in that case we loose lots of useful functionality from backbone. Is this a regression in Backbonejs 1.0 or am I using this model in the wrong way?

Upvotes: 1

Views: 1842

Answers (1)

recallfx
recallfx

Reputation: 146

There is a regression in Backbone.js 1.0, that is fixed in current master.

Closed issue

Upvotes: 1

Related Questions