Scalable Routing With Backbone

To scale up larger applications that rely on Backbone routing mechanisms, you can't rely on a single router instance. You need modular routers that are fit for a particular purpose.

by Adam Boduch

HTML

<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/2.4.1/lodash.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.0/backbone-min.js"></script>
<template id="template-main">
    <div><a href="#users">Users</a></div>
    <div><a href="#products">Products</a></div>
</template>

<template id="template-users">
    <h3>Users</h3>
    <ul></ul>
</template>

<template id="template-products">
    <h3>Products</h3>
    <ul></ul>
</template>

<div id="main"></div>

CSS

body {
    font: 0.8em Arial, Helvetica, sans-serif;
}

JavaScript

(function() {

    // The application "workspace" router. This router is container for all
    // collections used. In this case only two because it's an example. It also
    // only defines the default route - the homepage.    
    var ws = new (Backbone.Router.extend({
        
        routes: {
            "*path": "routeDefault"    
        },
        
        initialize: function() {
        
            // A dummy user collection.
            this.users = new Backbone.Collection([
                { name: "User 1" },
                { name: "User 2" },
                { name: "User 3" }
            ]);
            
            // A dummy product collection.
            this.products = new Backbone.Collection([
                { name: "Product 1" },
                { name: "Product 2" },
                { name: "Product 3" }
            ]);

        },
        
        // Displays the main page. It's not using views because that
        // detract from this demonstration. Instead it just renders
        // primitive HTML directly on the page. Same goes for the specialized
        // routers below.
        routeDefault: function() {
            $( "#main" ).html( $( "#template-main" ).html() );
        }
        
    }))();
    
    // The "users" router. This router is only concerned with routing
    // URLs that have to do with users.
    new (Backbone.Router.extend({

        // The routes.
        routes: {
            "users": "routeUsers",
            "users/:id": "routeUser"
        },

        // Stores the reference to the main "workspace" router, where all
        // application data is stored.
        initialize: function( options ) {
            this.ws = options.ws;    
        },

        // Routes the list of users. A real application would use a real
        // view here.
        routeUsers: function() {
            
            $( "#main" ).html( $( "#template-users" ).html() );
            
            this.ws.users.forEach(function( user )...