嗨,我正在学习骨干,但在将事件绑定到视图时遇到了麻烦。我的问题是我有一个视图构造函数,当调用它时,它将所有视图绑定到一个按钮按下事件,该事件只是一个视图的一部分。我希望按钮按下事件仅绑定到包含按钮的 1 个视图。
http://jsbin.com/tunazatu/6/edit?js,控制台,输出
- 单击所有视图按钮
- 然后点击返回查看1
- 单击红色按钮(所有视图的模型 console.log 他们的名字)
因此,我查看了这篇文章中的代码多重事件触发,这表明您可以拥有多个视图,这些视图具有相同的 el thru tagName 但仅将事件映射到它们的 html 元素。这也是 Jérôme Gravel-Niquet 的 localtodos 示例中所做的
我也尝试过不声明 el /tunazatu/7/edit?js,console,output 但似乎没有事件被绑定。
var AppView = Backbone.View.extend({
tagName:"div", //tagName defined
getName:function(){
console.log(this.model.get('name'));
},
initialize:function(options){
this.listenTo(this.model, 'change', this.render);
var temp_mapper = {appView1:'#route1',appView2:'#route2',appView3:'#route3'};
var m_name = this.model.get('name');
this.template = _.template($(temp_mapper[m_name]).html()); //choose the correct template
},
render:function(){
var temp = this.template(this.model.toJSON()); //populate the template with model data
var newElement = this.$el.html(temp); //put it in the view's tagName
$('#content').html(newElement);
},
events:{
"click button":"log"
},
log:function(){
this.getName();
}
});