O'Reilly logo

Developing Backbone.js Applications by Adnan Osmani

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

Problem

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:

this.$('.someContainer').append(innerView.el);

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

...
initialize : function () { 
    //...
},

render : function () {

    this.$el.empty();

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

    this.$('.inner-view-container')
        .append(this.innerView1.el)
        .append(this.innerView2.el);
}

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required