我有一个主干应用程序,它在一个函数中插入一个模板,在另一个函数中将一个部分模板插入该模板。问题是事件在第一个模板中绑定得很好,但在第二个模板中却绑定不好。通常,我会添加这样的事件:
events:{
'click .buttonOne': 'eventOne', //works
'click .buttonTwo': 'eventTwo' //doesnt work
},
但是,部分模板按钮不会绑定(不会触发任何事件)。我不确定这是什么原因。因此,为了克服这一点,我在插入分部时添加事件,如下所示:
$("#eventTwo").click(function(){
alert('test')
});
但是,即使我添加,我也无法获得"this"对象
var that = this
在事件绑定之前。我装订不正确吗?或者有没有办法让我得到我没有做的"这个"?
感谢
编辑:不起作用的完整代码示例
我的代码是这样工作的:当用户单击图像时,会触发一个事件(这是添加到主体中的模板。原始视图中的事件(即他们单击的图像)工作正常,但添加的模板不会。这是我的代码:
模板函数
template:function (renderOptions) {
//various case statements to determine which template to use
//returns the name of the template to use
return 'activityImages';
}
上面的模板有视图的html代码。最后,我有了这个:
<div id ="imageViewerDiv" class = "imageViewerDiv"></div>
然后,我在templateContext函数中添加模型:
templateContext:function (renderOptions) {
// builds out a list of objects and returns it to be used in the template
}
图像点击事件代码:
viewImage: function(e){
try{
var template = window.app.getTemplate('activityImageViewer')
var that = this;
//other variables defined here
//I am trying to create an effect that pops up a modal div, with the image in it
//in order for me to cover the entire app, i have to append this div to the body
$(document).find('body').append($("#imageViewerDiv"))
var temp = template({
//variables I need passed here
});
this.addImageToViewer(temp);
}catch(e){
throw e;
}
},
//here I add a partial template to the main template. this is where events fail to bind.
//in my template i have this, within a div, inside a table
<div id = "prevImgGalleryImg" name = "prevImgGalleryImg" style="float: right; padding-left: 10px; cursor: pointer;">Prev</div>
addImageToViewer: function(template){
try{
var that = this;
var temp = template;
$(document).find('body').append($("#imageViewerDiv"))
$("#imageViewerDiv").append(template);
//I add events here, as they do not bind any other way
$("#prevImgGalleryImg").click(function(){
//cant get this or that here
alert('test')
});
}catch(e){
throw e;
}
},
为了添加事件,我这样做,但不起作用:
events:{
//my events
'click .prevImgGalleryImg': 'prevImgGalleryImg'
},
prevImgGalleryImg: function(e){
alert('test');
},
解决方案:
经过一番挣扎,我终于想通了。当我添加div时,如下所示:
$(document).find('body').append($("#imageViewerDiv"))
我应该这样添加:
this.$el.append($("#imageViewerDiv"))
您的主干应该是这样的:
events:{
'click .buttonOne': 'eventOne', //works
'click .buttonTwo': 'eventTwo' //doesnt work
},
eventOne: function () {
console.log(this);
},
eventTwo: function () {
console.log(this);
}
现在,您可以正确访问此。不知道为什么我们使用jquery来附加事件。
希望这能有所帮助。
参见_.bind
和_.bindAll
。
从视图的构造函数/初始化函数调用_.bind
/_.bindAll
将强制执行正确的this
上下文:
var MyCustomView = Backbone.View.extend({
...,
events: {
'click .buttonOne': 'eventOne',
'click .buttonTwo': 'eventTwo'
},
initialize: function( options ) {
...;
_.bindAll(this, 'eventOne', 'eventTwo');
}
...,
eventOne: function( event ) {
// 'this' will always reference MyCustomView
},
eventTwo: function( event ) {
// 'this' will always reference MyCustomView
}
});