我有这样的代码。我点击按钮,它只工作几次。Chrome 说按钮上没有事件监听器。但是 View 创建按钮并且 View 有 click 事件。你能帮助我吗?
//buttons view
var NavigateBar = Backbone.View.extend({
events : {
'click button#back' : 'onBack',
'click button#next' : 'onNext',
'hover' : function() {console.log('hover on navigate')}
},
initialize: function(options) {
//buttons html
this.backDiv = '<button id="back" class="btn btn-primary btn-large pull-left">Back</button>';
this.nextDiv = '<button id="next" class="btn btn-primary btn-large pull-right">Next</button>';
//save options
this.back = this.options.back;
this.next = this.options.next;
},
//buttons event
onBack : function(e) {
e.preventDefault();
app.navigate(this.back, {trigger: true});
},
onNext : function(e) {
e.preventDefault();
app.navigate(this.next, {trigger: true});
},
//render
render: function() {
this.$el.html("");
this.$el.append(this.backDiv);
this.$el.append(this.nextDiv);
return this;
}
});
//create router class
var AppRouter = Backbone.Router.extend({
routes: {
"" : 'home',
":id" : 'test'
},
//create different views
initialize:function () {
this.homeView = new NavigateBar({
//pass options to view
back: "1",
next: "2"
});
this.testView = new NavigateBar({
back: "3",
next: ""
});
},
//route actions
home : function() {
$('#view-goes-here').html(this.homeView.render().el);
},
test : function(e) {
$('#view-goes-here').html(this.testView.render().el);
}
});
//create app
$(function(){
app = new AppRouter();
Backbone.history.start();
});
演示:http://jsfiddle.net/3Jaru/3/,点击下一步按钮两次,你会看到