Nested models of the same class in the Backbone.js structure?

I am new to Backbone.

Is it possible to define a model in a trunk that contains a list of models of the same type? Example:

MyModel = Backbone.Model.extend({ initialize: function() { nestedMyModels:new Array(); }, addMyModel: function(aModel) { // Code here would push() aModel onto array }, render: function() { // Loop through array calling render() recursively } }); 

Then I will have a view in which the recursive call to render () was started. Example:

 MyView = Backbone.View.extend({ render:function() { this.model.render(); } }); 
+1
source share
4 answers

1 no arrays but collections

Always what you think in Array of Models in Backbone, think in Collection .

Now you need to implement the MyModels collection and save one instance of this instance in your MyModel instance.

 // code simplified and not tested MyModel = Backbone.Model.extend({ initialize: function() { this.nestedMyModels: new MyModels(); }, addMyModel: function( model ) { this.nestedMyModels.add( model ); } }); MyModels = Backbone.Collection.extend({ model: MyModel }); 

2 use Views for rendering

Always what you think in render , think in View .

And it is recommended that if you have Collection and Model , it is better to have a View for each of them. Thus, the collection view will cause the model to be presented in iteration:

 // code simplified and not tested MyModelView = Backbone.View.extend({ render: function(){ this.$el.html( model.get("name") ); var view = new MyModelsView({ collection: this.model.nestedMyModels }); this.$el.append( view.render.el ); return this; } }); MyModelsView = Backbone.View.extend({ render: function(){ this.collection.each( function( model ){ var view = new MyModelView({ model: model }); this.$el.append( view.render.el ); }); return this; } }); 
+3
source

You want a collection . This is basically a list or an array of models.

0
source

Collections are ordered sets of models. Check for more information. http://backbonejs.org/#Collection

Here is an example:

 var Library = Backbone.Collection.extend({ model: Book }); 
0
source

Is it possible to identify a model in the spine that contains a list of Models of the same type?

Of course, why not.

 var MyModel = Nested.Model.extend(); MyModel.define({ defaults : { nestedMyModels : MyModel.Collection }, addMyModel: function( model ) { this.nestedMyModels.add( model ); } }); 

Just not in the vanilla layout. For this you need a plugin. https://github.com/Volicon/backbone.nestedTypes

PS: And as it was said in other answers, you need to use View for rendering. Not a model.

0
source

All Articles