Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / Javascript

Default Routing in Backbone

5.00/5 (1 vote)
6 Nov 2015CPOL 8.1K  
This tip is about how to enable default routing in backbone.js.

Introduction

Lately, I came across a situation where I need to navigate to a default routing if no routing matches with the routing is specified.

Say I have a user list page with the URL http://some-domain/user/list and there are two tabs for internal and external user. I have implemented backbone routing in such a way that user can directly navigate to particular tab using the URL like URL for navigating to internal user list is http://some-domain/user/list#internal and for external user it is http://some-domain/user/list#external.

Then, what we need to do is navigate to some default routing say http://some-domain/user/list#internal if there is no routing specified like when someone tries to access http://some-domain/user/list or any invalid routing like http://some-domain/user/list#invalid-route.

The below code demonstrates how we can solve that.

Using the Code

This is the backbone router we define.

JavaScript
var UserListRouter = Backbone.Router.extend({

            routes: {
                "internal": "showInternalUserTab",
                "external": "showExternalUserTab",
                "*action": "goToDefaultRoute"
            },

            showInternalUserTab: function() {
                Backbone.Events.trigger("activate:internalUserTab");
            },

            showExternalUserTab: function() {
                Backbone.Events.trigger("activate:externalUserTab");
            },

            goToDefaultRoute: function() {
                this.navigate("external", true);
            }
});

Here, we added one route "*action" to catch anything other than the route we provided. In the handler method of that route, we are specifying the default route to navigate.

History

  • 6th November, 2015: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)