1

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?

recallfx
  • 146
  • 7
  • I agree that it is expected from backbone to merge received properties to the specified defaults, but in this case, I am changing `selected` value to true _after_ we get that model from server. So the second time we fetch data from server, `selected` is already defined by initializer and changed by me. Using Backbone.js 0.9.10 with exactly the same code, is working differently in this jsfiddle: [http://jsfiddle.net/FH4Nj/](http://jsfiddle.net/FH4Nj/), the way I would expect: defaults are applied only to the missing values, not just different. – recallfx Jul 11 '13 at 08:57
  • A lot of people argue say that this isn't the way you're supposed to use Backbone. People like to keep the data on their models really pure. – Cory Danielson Jul 12 '13 at 02:40
  • But that is the way they show in Todo example! – recallfx Jul 23 '13 at 05:40

1 Answers1

1

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

Closed issue

recallfx
  • 146
  • 7