Snefs

a blog about javascript, ui, riots

A Backbone Router Is Not a Controller

There is a lot of discussion about the MVC approach embraced by Backbone. In my opinion, the way Backbone splits application into parts and reusable patterns, it’s closer to the Django approach than the Rails one.

There’s a main difference between Django and Rails: Model(s) apart, in Rails, you have Router, Controllers and Views (basically .erb templates). In Django, you have Urls, Views and Templates.

Essentially, what you call Controller in Rails, is a View in Django. And what you call Url config in Django is a Route in Rails. It’s a difference of nomenclature, by the way, but the point here is that both frameworks are splitting the application in three main parts:

  • Url routing
  • View/Controller
  • Template

So, in Backbone, you have Routers, Views and Templates. You don’t have any Controller. As in Django, you would use the Router to decide what view to call at certain url. Now, in the view, you are ready to:

  • fetch data on server
  • bind user interface to model state changes and any other event
  • render the data (model, collections, etc.) on a template

I think the pattern is very clear. By delegating as much as possible work to the view and the models, you will have a clear structure, avoid code repetition and use the router for what it was intended to do. So, use the Backbone router only to route urls to views. No data fetching. No user interface jobs. As said, do this kind of tasks in the View.

For concluding, it’s worth mentioning the fact that Backbone authors switched to call Router what they previously called Controller in the firsts versions of the framework.