我在Backbone中遇到一些非常简单的问题。我想在我的页面中连接<h1>
,以便当用户点击它时,它无缝地返回到主页,而不进行回发。
这是HTML:
<h1><a id="home" href="/">Home</a></h1>
(更新:评论者建议的固定ID。)这是我的Backbone视图和路由器:
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();
});
控制台正在向我展示
initialize app
initializing HomeView
但是当我点击<h1>
时,页面会回发 - 我在控制台中看不到goHome
。
我做错了什么?显然,我可以在jQuery中简单地连接<h1>
点击事件,但我想了解我应该如何在Backbone中进行此操作。
答案 0 :(得分:1)
如果启用pushState,则需要拦截所有点击并阻止刷新:
$('a').click(function (e) {
e.preventDefault();
app.router.navigate(e.target.pathname, true);
});
类似的东西:
$(document).ready(function(){
var HomeView = Backbone.View.extend({
initialize: function() {
console.log('initializing HomeView');
}
});
var AboutView = Backbone.View.extend({
initialize: function() {
console.log('initializing AboutView');
}
});
var AppRouter = Backbone.Router.extend({
routes: {
"": "index",
"about":"aboutView"
},
events: function () {
$('a').click(function (e) {
e.preventDefault();
SearchApp.navigate(e.target.pathname, true);
});
},
initialize: function(){
console.log('initialize app');
this.events();
this.HomeView = new HomeView();
},
index: function(){
this.HomeView = new HomeView();
},
aboutView : function() {
this.AboutView = new AboutView();
}
});
var SearchApp = new AppRouter();
Backbone.history.start({pushState: true});
});
答案 1 :(得分:1)
您的代码id
无效,请尝试以下操作:
<h1><a id="home" href="/">Home</a></h1>