Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I have generally seen/used a couple of different solutions:</p> <p><strong>Solution 1</strong></p> <pre><code>var OuterView = Backbone.View.extend({ initialize: function() { this.inner = new InnerView(); }, render: function() { this.$el.html(template); // or this.$el.empty() if you have no template this.$el.append(this.inner.$el); this.inner.render(); } }); var InnerView = Backbone.View.extend({ render: function() { this.$el.html(template); this.delegateEvents(); } }); </code></pre> <p>This is similar to your first example, with a few changes:</p> <ol> <li>The order in which you append the sub elements matters</li> <li>The outer view does not contain the html elements to be set on the inner view(s) (meaning you can still specify tagName in the inner view)</li> <li><code>render()</code> is called AFTER the inner view's element has been placed into the DOM, which is helpful if your inner view's <code>render()</code> method is placing/sizing itself on the page based on other elements' position/size (which is a common use case, in my experience)</li> </ol> <p><strong>Solution 2</strong></p> <pre><code>var OuterView = Backbone.View.extend({ initialize: function() { this.render(); }, render: function() { this.$el.html(template); // or this.$el.empty() if you have no template this.inner = new InnerView(); this.$el.append(this.inner.$el); } }); var InnerView = Backbone.View.extend({ initialize: function() { this.render(); }, render: function() { this.$el.html(template); } }); </code></pre> <p>Solution 2 may look cleaner, but it has caused some strange things in my experience and has affected performance negatively.</p> <p>I generally use Solution 1, for a couple of reasons:</p> <ol> <li>A lot of my views rely on already being in the DOM in their <code>render()</code> method</li> <li>When the outer view is re-rendered, views don't have to be re-initialized, which re-initialization can cause memory leaks and also cause freaky issues with existing bindings</li> </ol> <p>Keep in mind that if you are initializing a <code>new View()</code> every time <code>render()</code> is called, that initialization is going to call <code>delegateEvents()</code> anyway. So that shouldn't necessarily be a "con", as you've expressed.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload