I would like to know what is the recommaned way of nesting Backbone Views.
Possible ways to nest views:
I tried my luck already in this fiddle: http://jsfiddle.net/m48Nc/2/
Annotation: I know that the example doesn't work it just shows the structure, I figured out currently, but am not happy about it.
So which way is to go? Links are also welcome ;)
UPDATE:
Using fguillen answers and another thread I found we can do:
var IndexView = Backbone.View.extend({
tagName: "div",
className: "container",
template: LayoutTemplate,
render: function() {
this.$el.html(LayoutTemplate);
this.$('div.content').html(ContentTemplate);
this.$('div.sidebar').append(new LoginView().render().el);
this.$('div.sidebar').append(new RegistrationView().render().el);
return this;
}
});
You are using templates for dynamically append very complex elements one into each other. Templates are meant to dynamically append very simple Model.attributes.
I won't use a template for your MenuView. I'll define the Menu frame as a normal element into the HTML DOM and instantiate the MenuView assigning this DOM element to the View.el
like this:
var menuView = new MenuView({ el: "#menu" });
Then for render subViews into the MenuView I'll use jQuery append
, html
and more manipulation jQuery functionalities:
// code simplified and not tested
var MenuView = Backbone.View.extend({
render: function(){
// the this.$el is already rendered
// list of elements
this.collection.each( function( model ){
var modelView = new ModelView({ model: model });
this.$el.append( modelView.render().el );
}, this);
// additional subViews
var loginView = new LoginView();
this.$el.find( "div#login" ).html( loginView.render().el );
// another way to add subViews
var loginView = new LoginView({ el: this.$el.find( "div#login" ) });
loginView.render();
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With