Chapter 7. Common Problems and Solutions

In this section, we will review a number of common problems developers often experience once they’ve started to work on relatively nontrivial projects using Backbone.js, as well as present potential solutions.

Perhaps the most frequent of these questions surround how to do more with views. If you are interested in discovering how to work with nested views, and learn about view disposal and inheritance, this section will hopefully have you covered.

Working with Nested Views


What is the best approach for rendering and appending nested views (or subviews) in Backbone.js?

Solution 1

Since pages are composed of nested elements and Backbone views correspond to elements within the page, nesting views is an intuitive approach to managing a hierarchy of elements.

The best way to combine views is simply using:


which just relies on jQuery. We could use this in a real example as follows:

initialize : function () { 

render : function () {


    this.innerView1 = new Subview({options});
    this.innerView2 = new Subview({options});


Solution 2

Beginners sometimes also try using setElement to solve this problem; however, keep in mind that using this method is an easy way to shoot yourself in the foot. Avoid using this approach when the first solution is a viable option:

// Where we have previously defined ...

Get Developing Backbone.js Applications now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.