![](/img/trans.png)
[英]How to get the jQuery element (or attributes) in a click event in Backbone.js?
[英]How to handle a simple click event in Backbone.js?
我在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
不到goHome
。
我究竟做錯了什么? 很明顯,我可以在jQuery中簡單地連接<h1>
click事件,但我想了解我應該如何在Backbone中執行此操作。
如果啟用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});
});
您的代碼id
無效,請嘗試以下方法:
<h1><a id="home" href="/">Home</a></h1>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.