Using Backbone.js Support

Backbone.js is a powerful framework. If you’ve been following our blog, you have most likely noticed that we use it a lot. If you don’t have much background in it, take a look at the Backbone.js homepage or some of our articles to get you started. Although Backbone.js is powerful it lacks an automated way to clear views and unbind event bindings for garbage collection. With the help of a an extension known as Backbone Support, it’s easy to build views that automatically clean themselves up.

The first step of bringing Backbone Support into your project (after including the JavaScript file) is to extend the SwappingRouter in all of your routers. The SwappingRouter needs to know an element to grab hold of to place rendered views into. Whenever you want the router to show a new view, all you have to do is to new one up and pass it to @swap() for display. When @swap() is used, it unbinds and removes the previous view, to allow for garbage collection. Here is a sample:

TestApp = Support.SwappingRouter.extend(
  initialize: (options) ->
    @el = $(".random_element")

    foo: "index"
    bar: "bar"

  index: ->
    view = new TestApp.Views.FooIndex()
    @swap view

  bar: ->
    view = new TestApp.Views.Bar(model: new Baz())
    @swap view

The example uses CoffeeScript. You can see a little more about using Backbone.js and CoffeeScript in a previous post.

The next step is to extend Support.CompositeView to your views to provide supporting methods for managing child views. The methods provided help render and append child views to an element on the page via @renderChildInto() or appending it to the view’s element itself with @appendChild(). It also provides a @leave() method to allow the view to unbind and remove itself from the page.

For more information, give the Backbone Support github page a read. If you are in need of a more in-depth set of functionality, like @appendChildTo() or @prependChildTo() to place children within a specific element in the view, take a look at the fork from GitHub user domchristie.