Backbone.js: nesting views through templating

user802232 picture user802232 · Aug 18, 2011 · Viewed 15k times · Source

Is it technically possible to nest views, using templating, something like that:

<%= new PhotoCollectionView({model:new PhotoCollection(model.similarPhotos)}).render().el) %>

I can put all the stuff in the render method as well, but templating gives much more room for flexibility and layout.

I tried the aforementioned variant, but all I get as a result on the screen is [HTMLDivElement].

If I try to extract just the HTML out ouf it, using jQuery's HTML, I get it rendered, but it turns out that the DOM nodes that get printed out are different from the ones that the views hold a reference to, because no interaction whatsoever with those DOM nodes is possible using the view instance. For instance if within the view I say $(this.el).hide(), nothing will happen.

What is the proper way, if any?

Answer

Skylar Anderson picture Skylar Anderson · Aug 23, 2011

I typically render the parent view first. I then use the this.$('selector') method to find a child element that I can use as the el of the child view.

Here is a full example:

var ChildView = Backbone.View.extend({
  //..
})

var ParentView = Backbone.View.extend({
  template: _.template($('#parent-template').html()),
  initialize: function() {
    _.bindAll(this, 'render');
  }
  render: function() {
    var child_view = new ChildView({ el: this.$('#child-el') }); //This refers to ParentView. 
    return this;
  }
});

var v = new ParentView();
v.render();