What is Backbone.Router and Backbone.history?

Backbone history is a global router that keeps track of the history and lets us enable routing in the application. To instantiate a route and start tracking the navigation history, we need to create the router class and call Backbone.history.start to let the backbone start listening to routes and manage history. Backbone routes are simple objects that handle the incoming route value from the URL and invoke any function.

Why use them?

  1. Backbone routes and history enable us to extract URLs and use them to reach a specific view of a website.
  2. It allows us to use browser navigation within single pages of applications.
  3. It facilitates the possibility of having deep copied URLs.

Code

  1. First, we define the relevant source links that need to be utilized in order to access backbone objects.
<script src= 
"https://code.jquery.com/jquery-3.1.0.min.js"></script> 

<script src= 
"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script> 
  
<script src= "https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.3.3/backbone-min.js"></script>
  1. Next, we define three views using Backbone.View.Extend. Backbone views are used to reflect what your applications’ data models will look like. In the initialize function of the view object, we will define three different html messages to be displayed on the screen for all three view objects.

  2. We will now create a new router using Backbone.Router.extend. This router is given our view objects as routes and can redirect us to three views using these routes. Take a look at the implementation below:

By default, the router calls function Show_View1, which creates a new object of View_1 to display a message.

In order to call the Show_View2 function, we need to give view2 as a parameter to our file URL. For example, when you write the code in a notepad file named backbone_router.html, running it on the browser will run it on localhost. The URL will look something like this:

H:/backbone_router.html

Therefore, we give the following extension to the URL in the form of #/view2. Our URL will now become:

H:/backbone_router.html#/view2

Similarly, in order to call the Show_View3 function, we need to give view3 as a parameter to our file URL. Therefore, we give the following extension to the URL in the form of #/view3. Our URL will now become:

H:/backbone_router.html#/view3

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved