Home » Backbone » Backbone Routing

Backbone Routing

Routing is another key concept of backbone.js library which provides mechanism to support browser history and push state. Backbone provides mechanism of changing URL and performing an action using routers. Basically, Backbone routers respond to change in URL and perform an action based on the URL value. For example, if you want to display some splash screen when user comes on home screen then you can check the URL value and if its home then you can call a method to display the splash screen. Let’s create an example to understand the backbone routing concept.

Below is the basic backbone router:

 var Router = Backbone.Router.extend({
                // in routes property you have "route_name":"action_to_perform"
                routes:{
                   'pageOne':'displayPageOne', // whenever the URL changes to hostName/index.html#pageOne - call displayPageOne() function
                   'pageTwo/:keyword':'displayPageTwo' // whenever the URL changes to hostName/index.html#pageTwo/paramters - call displayPageOne(params) function
                },
                displayPageOne:function(){
                  // call this function when URL changes to hostName/index.html#pageOne
                 // TO-DO
                },
                displayPageTwo:function(keyword){
                  // call this function when URL changes to hostName/index.html#pageTwo/paramters
                 // TO-DO
                }
});

  - In routes property you just define key, value pair of route name and function.

 - You can pass parameters also like I did for “pageTwo”.

I prefer to have one router per application but there is no such hard and fast rule. Generally one router solves the purpose.

 

Defining routes and Navigation

Above example shows how you can define the router in backbone application. Let’s add some more code to make it work.

// Backbone view with button
var PageOne = Backbone.View.extend({
                initialize:function(){
                  // initialize will render the view
                  this.render();
                },
                events:{
                  "click #id_pageTwo":"showPageTwo"
                },
                showPageTwo:function(){
                   // Will navigate to pageTwo/Vehicle URL
                   Backbone.history.navigate('pageTwo/Vehicle',{trigger:true});
                },
                render:function(){
                   $('body').empty();
                   var pageOneHtml = "<h1>This is Page one</h1><button id='id_pageTwo'> Page Two</button>";
                   this.$el.html(pageOneHtml);
                }
         });
var PageTwo = Backbone.View.extend({
                initialize:function(){
                        this.render();
                },
                events:{
                   // another way of calling function on button click
                  "click #id_pageOne":function(){
                      // Will navigate to pageOne URL
                      Backbone.history.navigate('pageOne',{trigger:true});
                   }
                },
                render:function(){
                   $('body').empty();
                   var pageTwoHtml = "<h1>This is Page Two</h1><button id='id_pageOne'>Back</button>";
                   this.$el.html(pageTwoHtml);
                }
     });

var Router = Backbone.Router.extend({
                routes:{
                  'pageOne':'displayPageOne',
                  'pageTwo/:keyword':'displayPageTwo'
                },
                displayPageOne:function(){
                  var pageOne = new PageOne();
                  $('body').append(pageOne.$el);
                },
                displayPageTwo:function(keyword){
                   console.log(keyword);
                   var pageTwo = new PageTwo();
                   $('body').append(pageTwo.$el);
                }
      });

var router = new Router();

// start the browser History
Backbone.history.start();

// display navigate to pageOne on page load
router.navigate('pageOne',{trigger:true});

 

Above code has two Views “pageOne” and “pageTwo”. First view has a button, clicking on which will change the URL to pageTwo/Vehicle. Now the control will go to route and check if this route name exists and then will call corresponding function, i.e. in this case it will call “displayPageTwo” and pass “Vehicle” as parameter. Second Page has a back button which change the URL to pageOne. So its pretty much simple, you just need to check the URL value and perform an action based on that value.

Above code use some router concepts; let’s go over each one of them:

  • Backbone.history: Backbone.history automatically handles the hashChange and pushState events.
  • Backbone.history.navigate(): this function will change browser address to given URL, without doing the page navigation. If you want to navigate the page, then you can pass {trigger:true}.
  • Backbone.history.start(): Once everything is at place, you need to create an instance of router and start monitoring the hashChange. To do that you should call Backbone.history.start(). In simpler words, this method is basically used to start the routing. You can use Backbone.history.start({pushState: true}) for HTML5 supported browsers or Backbone.history.start({pushState: true,  hashChange: false}) for non-supported browsers.

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>