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

Create sub models at initialization #135

Closed tolbahadi closed 10 years ago

tolbahadi commented 10 years ago

Is there an option that allows the associated model to create its sub models/collections at initialization time? I have been using defaults object to have it do this but I was sure if this was the best practice or not.

Example:

var Model = Backbone.AssociatedModel.extend({
    relations: [{
        type: Backbone.One,
        key: 'class',
        relatedModel: ClassModel
    }, {
        type: Backbone.Many,
        key: 'students',
        relatedModel: StudentModel
    }],
    defaults: {
        class: {},
        students: []
    }
});

var model = new Model();

var classModel = model.get('class');
var classView = new ClassView({model: classModel});

var studentsCollection = model.get('students');
var studentsView = new StudentsView({collection: studentCollection});

Is there a way I can do this without using the defaults object?

dhruvaray commented 10 years ago

What you have done is ok. You can also pass in empty or non-empty sub-models/collections too.

model = new Model({class:{}, students:[]});