user396004
user396004

Reputation: 285

Backbone and Marionette convention for representing an itemview that is an object and a collection

So I have an object that looks something like this

{
  first_name: 'Matt',
  last_name: 'Damon',
  movies: [{name: 'mov_name1', director: 'Sven'}, {name:'mov_name2', director: 'Joe'}]
}

There is an endpoint that will return this, and I will use fetch to get this data and put it in a model or ItemView. (I have to use fetch because I really want a collection of these objects, so I'll call fetch on the collection.) However, the representation of the object should not be a model alone, it should be a model (or ItemView), and the movies attribute should be a collection, since when I display the row for this object it should be a CompositeView with a model and a collection. My question is how do I convert this object representation to a model and collection after a fetch called on the model?

Sorry it's a bit confusing to explain...

Upvotes: 1

Views: 176

Answers (2)

anil
anil

Reputation: 61

If its not a problem to use another framework, there is one called backbone-relational. It is designed to handle the relations between models. See the zoo example in Backbone-Relational

In the example there is a Zoo model and models has a Animal Collection which consist of animal models. With a single fetch on Zoo model, you will have the animal collection as Backbone collection instead of array of plain objects.

Upvotes: 0

Rayweb_on
Rayweb_on

Reputation: 3727

do a fetch on your collection and then for each element create a model and a collection that you can pass then to a compositeView

something like this

  mycollection = new MyCollection();
  mycollection.fetch();
  mycollection.each(function(item){
      var actorModel = new ActorModel({firstName : item.get('first_name'),
                               lastname: item.get('last_name')});
      var moviesCollection = new MoviesCollection(item.get('movies'));
      var xCompositeView = new XCompositeView({model:xmodel,
                                               collection:moviesCollection});
  });

this way your Compositeview gets a model and a collection and you can render them properly using an itemView for each movie.

hope this helps.

Upvotes: 2

Related Questions