Tuesday, January 21, 2014

Scalable Routing With Backbone

The typical Backbone application, at least the demo applications you'll find, use a single router instance to manage URLs. That's fine because where there are only a handful of possible URLs the application understands, creating more than one router instance is overkill. What I find strange, however, are the lack of examples that use multiple routers. Backbone exposes the router as a component to be extended and instantiated. It's by no means a singleton.

Maybe it's the lack of documentation that leaves developers reluctant to use more than one router. So, I decided to experiment myself. Here's a demonstration of running multiple routers for the same application. And please excuse the contrived nature of the app — it's purely meant as an example on how to run a Backbone application using multiple routers. It doesn't even use views for instance.

It wasn't till after I implemented both routers that I saw the real potential of multiple routers to abstract-away complexity. Part of the issue is that a single router will quickly grow out of control as more and more features are added to the UI. The idea of using multiple routers to separate concerns from one another makes sense.

For example, the application I've implemented uses a main "workspace" router, and two domain-specific routers. The workspace is the central point of sharing. That is, collections get created and stored here so they may be shared by the other routers, and ultimately, the views that make up the UI. The user and product routers get created with an instance of the workspace router. They both hold onto a reference of the workspace so that if they need access to any collection in the application, they have it.

But I think the really powerful aspect of this approach to routing is the modularity of each router. That's what makes it scalable. Once a single router becomes too complex, it fails to scale. Routers that focus on a cohesive set of application concerns can live in their own module. Even inside an AMD module, which is important given the direction web applications are moving.