Using Marionette.js with Backbone

Article summary

I’ve recently had the opportunity to work on a single page web application built on top of Backbone.js. While I love the simplicity of the Backbone framework and source code, I was looking for something a little more opinionated to build my view layer on top of, specifically something that would help with lifecycle management.

I came across the Marionette library, and have enjoyed using it so far. It’s saved me a fair amount of time I would have spent writing boilerplate to manage my views and compose nested structures.

Regions

You can do some nice things with Marionette, starting with creating application regions:

app = new Backbone.Marionette.Application()
app.addRegions
  navigation : '#navigation'
  header     : '#header',
  main       : '#main',
  footer     : '#footer'

Once defined, you can set views to those regions:

app.navigation.show new NavigationView()
app.main.show new TodosView()

And Marionette automatically handles disposing any previously displayed views for you so that you don’t have to worry about zombies hanging around. Any event bindings added to the model, collection, and DOM elements are released for you when your view is closed.

ItemView

The ItemView adds a lot of nice behavior in addition to what the base Backbone View class provides. I have some Marionette views that are as trivial as defining a template property:

class PageHeaderView extends Backbone.Marionette.ItemView
  template: Templates.page_header

Marionette’s ItemView renders the defined template passing the view’s model serialized via toJSON() so that your template can grab properties off the model without any extra work to wire things up. You can of course override this behavior to provide a different set of values to your template.

Another nice bit of sugar is the ui mapping. You can define elements that you’re interested in by css selector:

ui:
  actions: "#actions"
  saveButton: "button#save"

And the fields will be populated for you so that you can later run something like:

@ui.actions.hide()

Instead of running a search each time to locate an element before making your method call.

Other Notes

Marionette includes a CollectionView, which has nice support for rendering a child view for each item in a given collection. I’ve also found the CompositeView (renders both an ItemView for a model and child views for each element in a collection) and the Layout classes helpful in creating nested view structures.

There are pieces of Marionette that I’ve chosen not to use, but fortunately there’s no tight coupling between the various components available — you can pick the bits you want to use without being locked in to the entire library. Another nice feature is that Marionette will generally take any Backbone View object for its regions or layouts, so you can mix and match Marionette code with plain Backbone views.