0
votes

I have a Backbone App with 3 model which have nested collections:

Models Structure:

Layout extends Backbone.Model
-> sections: new Sections extends Backbone.Collection


Section extends Backbone.Model
-> rows: new Rows extends Backbone.Collection

Now if I have two section model in layout and I go and add row model to one of the Section.rows collection, it is adding it to both sections.

BTW, I am adding it from a view on an event.

Thanks in Advance.

2

2 Answers

0
votes

got a workaround. I could reproduce your workflow by adding defaults property to my models.

like this:

var Section = Backbone.Model.extend({
    defaults: {
        rows: new Rows
    }
});

var Layout = Backbone.Model.extend({
    defaults: {
        sections: new Sections
    }
});

then really, if i add new row to rows to one of my section its appear to adding to all sections rows collection. So i do this (rude example):

var Row = Backbone.Model.extend({
    defaults: {
        rowData: 0
    }
});

var Rows = Backbone.Collection.extend({
    model: Row
});

var Section = Backbone.Model.extend({
    //defaults: {
    //    rows: new Rows
    //}
});

var Sections = Backbone.Collection.extend({
    model: Section
});

var Layout = Backbone.Model.extend({
    //defaults: {
    //    sections: new Sections
    //}
});

var LayoutView = Backbone.View.extend({

});

var lView = new LayoutView({ model: new Layout });
lView.model.set('sections',new Sections());
var sections = lView.model.get('sections');
sections.add({id: 1, name: 's1',rows: new Rows() });
sections.add({id: 2, name: 's2',rows: new Rows() })
var rows = sections.get(1).get('rows');
rows.add({id:'r1',rowsData: 10});
console.log(lView.model.toJSON());
0
votes

@aleha you are right the issue is of the default attribute settings in Model. As they share the same memoery space(javascript: pass by reference not by value ).

So what I did is in the initialize function

initialize: function() {
    this.set( 'rows', new Rows() );
}

So, no need to do it like you are doing above:

sections.add({id: 1, name: 's1',rows: new Rows() });

Hence resolved and automate :)

Thanks for the help though.