dhruvaray/backbone-associations

Collections become empty when using collection initialize

Closed this issue · 3 comments

Hi,

I have a one-to-many relation, where i always need one item on the many side. If the server does not have this data (from a previous time) then an empty model should be inserted into the collection. Taken the example from the documentation i try to do this:

var Location = Backbone.AssociatedModel.extend({

});

var Locations = Backbone.Collection.extend({
    model: Location,

    initialize: function() {
        console.log(this, this.length); // empty collection, 0
        if (this.length === 0) {
            this.add([{}]);
        }
        console.log(this, this.length); // collection with 1 Location, 1
    }
});

var Project = Backbone.AssociatedModel.extend({
    relations: [
        {
            type: Backbone.Many,
            key: 'locations',
            collectionType: Locations,
            relatedModel: Location
        }
    ]
});

I initialize it like this:

var project = new Project(rawProjectData);
console.log(project); // project has collection of Locations, but collection is empty !!

I couldn't find a related question about collection initialization. Perhaps i'm using the wrong pattern here? I really want to avoid having to send empty data from the server, but let the client side initialize new models instead.

You may want to look at issue #121.

@flip111

I have a one-to-many relation, where i always need one item on the many side. If the server does not have this data (from a previous time) then an empty model should be inserted into the collection.

Your scenario can be handled easily like this

var Location = Backbone.AssociatedModel.extend({

});

var Project = Backbone.AssociatedModel.extend({
    relations: [
        {
            type: Backbone.Many,
            key: 'locations',
            relatedModel: Location
        }
    ],
    defaults : {'locations':[{}]}
});

var p = new Project;
console.log(p.get('locations').length) //1

Hi, thanks for this solution.

Two remarks though.

  1. It's not very intuitive because it's now put with a model instead with the collection.
  2. Also not really DRY when you want to reuse the collection somewhere.

But for my use case the proposed solution will do. thank you