jrsalunga
jrsalunga

Reputation: 419

Backbone inherit model2 attribute from model1 attribute

I have a models and collection

Model1 = Backbone.Model.extend();
Model2 = Backbone.Model.extend({
    defaults: {
        code:'',
        m1_id: ?????, // this part should get the Model1 "id" attribute
        id: ''        //                 e.g. the value of m1.get('id');
     }
});

C = Backbone.Collection.extend({ 
    model: Model2
});

and make an instance of each

var m1 = new Model1();
var m2 = new Model2();
var c = new C();

and set the values

m1.set({'code':'0001', 'type': 'O', id: 1});

c.add({'code':'sample1', 'id':1});  // note: i did not set the m1_id
c.add({'code':'sample2', 'id':2});

but the model inside collection get the Model1 id attrtibute, something like

the Collection must have this

c.at(0).toJSON();
-> {'code':'sample1', 'm1_id': 1, id: 1}  // note: the "m1_id" value is 
c.at(1).toJSON();                         //       from Model1 "id" attribute 
-> {'code':'sample2', 'm1_id': 1, id: 2}

How i can automatically set the Model2 attribute inside the Collection from the Model1 attribute.. Thanks!

Upvotes: 1

Views: 98

Answers (2)

jrsalunga
jrsalunga

Reputation: 419

Model1 = Backbone.Model.extend();
var m1 = new Model1();

Model2 = Backbone.Model.extend({
    defaults: {
        code:'',
        m1_id: '', 
        id: ''       
     }
});
var m2 = new Model2();


C = Backbone.Collection.extend({ 
    model: Model2,
    initialize: function(){
        this.on('add', this.onAddModel, this);
    },
    onAddModel: function(model){    
         model.set({'m1_id': m1.get('id')});
    }
});
var c = new C();


m1.set({'code':'0001', 'type': 'O', id: 1});
c.add({'code':'sample1', 'id':1}); // trigger the c.onAddModel function
c.at(0).toJSON();
-> {'code':'sample1', 'm1_id': 1, id: 1}

Upvotes: 0

user2551866
user2551866

Reputation: 223

Firstly, you have some problem with your code:

var m1, m2, and c should be called with the keyword: new to instantiate your models and collections

e.g. var m1 = new Model1()

your code to add to your collection (c.add) is also missing the closing curly brace

c.add({'code':'sample1'); // should be c.add({code:"sample1"});

Your code and question isn't completely clear to me, but I suspect you may be trying to add a model to your collection with the same id perhaps. Multiple models of the same id won't get added to your collection, as per the backbone documentation:

Note that adding the same model (a model with the same id) to a collection more than once is a no-op.

If you need to to pass the id from another model, you'd need to set another attribute like you have "parent_id" on passing it to your collection.

e.g var temp_id = m1.get('id'); c.add({code:"sample3", id:temp_id});

Upvotes: 3

Related Questions