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.
<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>
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.
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:
Therefore, we give the following extension to the URL in the form of
#/view2. Our URL will now become:
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:
View all Courses