dhruvaray / backbone-associations

Create object hierarchies with Backbone models; Respond to hierarchy changes using regular Backbone events.
http://dhruvaray.github.io/backbone-associations/
MIT License
492 stars 75 forks source link

Collections become empty when using collection initialize #130

Closed flip111 closed 10 years ago

flip111 commented 10 years ago

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.

jdkanani commented 10 years ago

You may want to look at issue https://github.com/dhruvaray/backbone-associations/issues/121.

dhruvaray commented 10 years ago

@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
flip111 commented 10 years ago

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