I am having difficulty with something very simple in Backbone. I want to wire up the <h1>
in my page so that when the user clicks on it, it returns seamlessly to the homepage, without a postback.
This is the HTML:
<h1><a id="home" href="/">Home</a></h1>
(UPDATE: fixed ID as suggested by commenter.) And this is my Backbone view and router:
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(){
// do stuff here
},
start: function(){
Backbone.history.start({pushState: true});
}
}));
$(document).ready(function() {
SearchApp.start();
});
The console is showing me
initialize app
initializing HomeView
But when I click on the <h1>
, the page posts back - and I don't see goHome
in the console.
What am I doing wrong? Clearly I can wire up the <h1>
click event simply enough in jQuery, but I want to understand how I should be doing it in Backbone.
If you enable pushState you need to intercept all clicks and prevent the refresh:
Something like:
Your tag
id
is invalid, try this: