Click here to Skip to main content
15,886,035 members
Articles / Programming Languages / Javascript
Tip/Trick

Default Routing in Backbone

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
6 Nov 2015CPOL 7.8K   2  
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)


Written By
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --