What are routers in Backbone.js?

Backbone routers are used for routing your applications URL’s when using hash tags(#). In the traditional MVC sense they don’t necessarily fit the semantics. Though a Backbone “router” is still very useful for any application/feature that needs URL routing/history capabilities.

Backbone Rrouter
Backbone Rrouter

Defined routers should always contain at least one route and a function to map the particular route to. In the example below we are going to define a route that is always called.

Also note that routes interpret anything after “#” tag in the URL. All links in your application should target “#/action” or “#action”. (Appending a forward slash after the hashtag looks a bit nicer e.g. http://example.com/#/user/help)

Activate route

Activate another route

Notice the change in the url

Dynamic Routing

Most conventional frameworks allow you to define routes that contain a mix of static and dynamic route parameters. For example you might want to retrieve a post with a variable id with a friendly URL string. Such that your URL would look like “http://example.com/#/posts/12”. Once this route was activated you would want to access the id given in the URL string. This example is implemented below.

Post 120

Post 130

Notice the change in the url

Dynamic Routing Cont. “:params” and “*splats”

Backbone uses two styles of variables when implementing routes. First there are “:params” which match any URL components between slashes. Then there are “splats” which match any number of URL components. Note that due to the nature of a “splat” it will always be the last variable in your URL as it will match any and all components.

Any “*splats” or “:params” in route definitions are passed as arguments (in respective order) to the associated function. A route defined as “/:route/:action” will pass 2 variables (“route” and “action”) to the callback function. (If this is confusing please post a comment and I will try articulate it better)

Here are some examples of using “:params” and “*splats” :

routes: {
    "posts/:id": "getPost",
    //Example"download/*path": "downloadFile",
    //Download":route/:action": "loadView",
    //LoadRoute/ActionView
},
app_router.on('route: getPost',
    function (id) {
        alert(id); //121
    }
);
app_router.on('route: downloadFile',
    function (path) {
        alert(path); //user/images/hey.gif
    }
);
app_router.on('route: loadView',
    function (route,action) {
        alert(route + "_" + action); //dashboard_graph
    }
);

One can call navigate on the router instance specifying the route to navigate:

app_router.navigate('newRoute', {trigger: true});

The first argument to the navigate method specifies to which route the application should be routed. The second argument to the navigate method is an object where the ‘trigger’ key is set to true. This indicates that you want to update the URL as well as trigger the route function for the specified route. If trigger is set to false or if trigger is not specified then only the URL would be updated and the function defined for that route would not be invoked.

Parameters & Splats

If you have ever done web development using dynamic pages of any kind, you know that the content on pages are populated depending on the parameters that get passed in.

So, for example, if you had a social profile of some sort, you might have something like http://www.roymj.co.in/profile.php?id=1&view=all. In that case, the parameters “id” and “view” would be used by the website to determine who’d profile to show and how to show it. You would have one view that defined the layout and what you’d show in that view would depend on the specific parameters.

Backbone.js applications have the ability for you to pass in parameters as well.

Let’s add yet another route such that our code looks like the following :

var Router = Backbone.Router.extend({
  routes: {
    "": "home", // url:event that fires
    "new": "createNew"
    "edit/:id": "editItem",
  }
});
var router = new Router;

And in the place where we have added our “on” methods add the following (but, again, before the Backbone.history.start(); statement).

router.on('route:editItem', function(idParam) {
    alert('We are going to edit entry number ' + idParam);
});

So obviously we are going to try to catch an event when the user goes to http://www.yourwebsite.com/#/edit,

but what is that :id thing?

This is how Backbone defines a parameter. Backbone is looking for a specific item to follow the

http://www.example.com/#/edit.

What happens if we go to the following URL?

http://www.example.com/#/edit

Nothing happened. Why is that? It’s because Backbone is expecting a parameter as we defined in our route.

So now try this :

http://www.example.com/#/edit/1

Now we see that backbone is catching the id parameter and it’s getting passed into the function. This is how we can populate a single view in Backbone and have variable content passed in.

What if we went to the following URL ?

http://www.example.com/#/edit/1/roy
Again nothing happens because this is passing in 2 parameters. To catch it we’d have to add another route as follows :
var Router = Backbone.Router.extend({
  routes: {
    "": "home", // url:event that fires
    "new": "createNew"
    "edit/:id": "editItem",
     "edit/:id/:name": "editItemAndName",
  }
});
var router = new Router;

And catch the event here :

router.on('route:editItemAndName', function(idParam, nameParam) {
    alert('We are going to edit entry number ' + idParam + 'and name ' + nameParam);
});

Now if we go to the URL http://www.example.com/#/edit/1/roy we can see that the event gets caught.

Backbone also has a special variable type of parameter called a “splat.”

A splat looks like the following :

var Router = Backbone.Router.extend({
  routes: {
    "": "home", // url:event that fires
    "new": "createNew"
    "edit/:id": "editItem",
    "edit/:id/:name": "editItemAndName",
    "download/*anything": "downloadItem"
  }
});
var router = new Router;

A spat basically means “match anything and everything”, so as a result if you were going to use a splat you would want to set it as the last item in your defined route.

So if put a place to respond to this event,

router.on('route:downloadItem', function(anythingParam) {
    alert('What is stored in anything is ' + anythingParam);
});

If we pass anything after /#/download/ all of it (slashes and all) will get passed to the anythingParam argument. If we go to http://www.example.com/#/download nothing happens because Backbone is still expecting a parameter.

However if we go to something like http://www.example.com/#/download/path/to/my/file we can see that path/to/my/file gets passed into the parameter (slashes and all)

Routes are quite powerful and in an ideal world your application should never contain too many.

5 Comments on "What are routers in Backbone.js?"


  1. Hey! I could have sworn I’ve been to this website before but after reading through some
    of the post I realized it’s new to me. Anyhow, I’m
    definitely happy I found it and I’ll be bookmarking and checking back frequently!

    Reply

  2. Its like you read my thoughts! You appear to understand
    so much about this, such as you wrote the e-book in it or something.
    I feel that you just could do with a few % to power the message home
    a bit, but other than that, this is excellent blog.
    A great read. I’ll certainly be back.

    Reply

  3. I am curious to find out what blog system you happen to be utilizing?
    I’m experiencing some small security issues
    with my latest website and I would like to find something
    more risk-free. Do you have any recommendations?

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *