Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the recommended way to nest views?

I would like to know what is the recommaned way of nesting Backbone Views.

Possible ways to nest views:

  1. Render all views and put them together in the Router
  2. Let an IndexView do all the nesting which is called in the router
  3. Include views in underscore templates

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;
    }

});
like image 492
bodokaiser Avatar asked Nov 03 '22 19:11

bodokaiser


1 Answers

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();
  }
});
like image 157
fguillen Avatar answered Nov 09 '22 10:11

fguillen