2

I have a fetch request which response looks like this.

response = {
   id: 1,
   title: 'text',
   followers: [{}, {}] // array of objects
}

As you can see the response is an object which have an attribute follower which is an array of object.

I would like to create from this response one model and one collection, one which have the following attributes:

response = {
   id: 1,
   title: 'text'
}

and the other one, a collection of models

followers: [{}, {}];

What is the appropriate way to active my goal?
Could I use Backbone.Relation?
If yes, there are some example?

Derick Bailey
  • 72,004
  • 22
  • 206
  • 219
Lorraine Bernard
  • 13,000
  • 23
  • 82
  • 134

3 Answers3

2

I'm used to use the same approach than @lecstor but I like more do it in the initialize() like this:

initialize: function(){
  this.followers = new Followers( this.get("followers") );
}
fguillen
  • 36,125
  • 23
  • 149
  • 210
  • And what about putting in `initialise function` the following line? `this.on('change', this.create Followers, this);` – Lorraine Bernard May 31 '12 at 09:06
  • @LorraineBernard you have to be sure the attributes are seted after this _binding_ is declared, also beware this _binding_ will be called in any change in any _attribute_ of the _Model_. I suggest you will have to combine my approach with some kind of _binding_ that manage changes in the _followers_ attribute. – fguillen Jun 01 '12 at 08:11
1

depending on your needs/views/etc, I would probably wrap that response in a model and create a collection of models for followers...

MyModel = Backbone.Model.extend({
    urlRoot: '/url/to/get/response'
});

Follower = Backbone.Model.extend();

Followers = Backbone.Collection.extend({
    model: Follower
});

this.model = new MyModel({ id: 1 });
var that = this;
this.model.fetch({
    success: function(model, response){
        that.collection = new Followers( model.get('followers') )
    }
});

I think you could then update your model from the collection quite easily with:

this.model.set('followers', this.collection.toJSON())
lecstor
  • 5,619
  • 21
  • 27
0

why not have a model that contains the collections and sub-models?

essentially a view-model

MarkKGreenway
  • 8,494
  • 5
  • 34
  • 53