65.9K
CodeProject is changing. Read more.
Home

Default Routing in Backbone

starIconstarIconstarIconstarIconstarIcon

5.00/5 (1 vote)

Nov 6, 2015

CPOL
viewsIcon

8082

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.

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