如何处理在Backbone.js的一个简单的单击事件? [英] How to handle a simple click event in Backbone.js?
问题描述
我有东西主干很简单的难度。我想连线了< H1>
在我的网页,这样,当用户点击它,它无缝地返回到主页,没有回发。
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.
这是HTML:
<h1><a id="home" href="/">Home</a></h1>
(更新:固定的ID如评论者建议。)这是我的看法主干和路由器的:
(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();
});
该控制台显示我
initialize app
initializing HomeView
但是,当我点击&LT; H1&GT;
,页面回 - 我没有看到 GOHOME
在控制台中。
But when I click on the <h1>
, the page posts back - and I don't see goHome
in the console.
我是什么做错了吗? jQuery中单击事件只是够了,但我想知道我应该如何在骨干网做,显然,我可以连线了&LT; H1过夜。
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.
推荐答案
如果您启用pushState的需要拦截所有的点击和prevent刷新:
If you enable pushState you need to intercept all clicks and prevent the refresh:
$('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});
});
这篇关于如何处理在Backbone.js的一个简单的单击事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!