2
votes

I have a model with a backbone collection as an attribute. When I create a new model and save it along with its collection to the database it all works fine.

However, when I create a new model, its collection contains the previous models values. All the other properties are blank as expected.

I've defined my model defaults like this:

defaults: {
        InsertionOrderNumber: null,
        ClientID: null,
        CampaignName: null,
        FromDate: null,
        ToDate: null,
        TotalBudget: null,
        ManagementFee: null,
        AgencyCommission: null,
        SourceDocuments: new Uploads() //this is the collection
    }

For some reason it seems like the same instance of the collection is being used for all new models of that type.

Any idea why this is happening?

Thanks in advance =)

1

1 Answers

1
votes

As is, new Uploads() is evaluated when you define your model, not when you create a new instance. Use a function to create new collections in the defaults:

var M = Backbone.Model.extend({
    defaults: function() {
        return {
            InsertionOrderNumber: null,
            ClientID: null,
            CampaignName: null,
            FromDate: null,
            ToDate: null,
            TotalBudget: null,
            ManagementFee: null,
            AgencyCommission: null,
            SourceDocuments: new Uploads()
        };
    }
});

And a demo http://jsfiddle.net/nikoshr/gzTgt/