I am facing a challenge with a basic functionality in Backbone. I am trying to set up the <h1>
element on my page so that when a user clicks on it, it smoothly navigates back to the homepage without a page reload.
Here is the HTML snippet:
<h1><a id="home" href="/">Home</a></h1>
(UPDATE: corrected the ID as per the suggestion from a commenter.) Below is my Backbone view and router code:
var HomeView = Backbone.View.extend({
initialize: function() {
console.log('initializing HomeView');
},
events: {
"click a#home": "goHome"
},
goHome: function(e) {
console.log('goHome');
e.preventDefault();
SearchApp.navigate("/");
}
});
var SearchApp = new (Backbone.Router.extend({
routes: {
"": "index",
},
initialize: function(){
console.log('initialize app');
this.HomeView = new HomeView();
},
index: function(){
// perform actions here
},
start: function(){
Backbone.history.start({pushState: true});
}
}));
$(document).ready(function() {
SearchApp.start();
});
The console output displays
initialize app
initializing HomeView
However, when clicking on the <h1>
, the page reloads - and goHome
is not logged in the console.
What could be the issue here? While I can easily achieve the click event binding for <h1>
using jQuery, I am keen to grasp the correct approach in Backbone.