$(这个)没有使用cofeescript和backbone.Its生成有效的代码,但我不明白为什么它不起作用。为了解决我使用$(event.target)。
Jobmatch.Views.Jobs ||= {}
class Jobmatch.Views.Jobs.JobView extends Backbone.View
template: JST["recommendation/templates/jobs/job"]
initialize: () ->
@ajs = new Jobmatch.Collections.ApplicantJobsCollection()
@ajs.reset(@options.applicant_jobs || [])
@aj = new @ajs.model()
@index = @options.index || 0
events:
"click .job_apply" : "apply"
tagName: "tr"
apply: (event)->
target = $(this) // As this is not working as I expected,So I used below line.
target = $(event.target)
if @options.user_jobmatch_valid
@ajs.create({job_id: @model.get('id') })
target.parents("a.job_apply").prev().click();
else
target.parents("a.job_apply").next().click();
false
render: ->
$(this.el).html(@template(@model.toJSON()))
@
这个cofeescript生成了以下代码:
JobView.prototype.apply = function(event) {
var target; target = $(this); // not working it is not elementt object
target = $(event.target);// this is element object ,working fine
target.parents("a.job_apply").prev().click();
};
答案 0 :(得分:2)
在主干文档中,http://backbonejs.org/#View-delegateEvents 它明确指出:
所有附加的回调都会在传递之前绑定到视图 到jQuery,所以当调用回调时,这继续引用 到视图对象。
这解决了许多面向对象程序员使用jQuery的问题之一,它覆盖了所有事件处理程序中的上下文。如前所述,您通常可以使用事件,该事件作为处理程序的参数传递。但是,event.target
通常可以引用子元素而不是this
,它始终引用通过查询选择的元素。例如:
<a href="#"><b>my link</b></a>
$('a').on('click', myfunction); function myfunction(event) {
this // refers to the "a" element
event.target // refers to the "b" element
}
在这些情况下,将带有Backbone的鼠标事件附加到带子项的元素时,使用event.currentTarget
获取对事件处理程序附加到的元素的引用。
events: {
"click a" : "myFunction" },
...
function myFunction(event) {
var $this = $(event.currentTarget);
// Now, $this is the same as jQuery's $(this)
}
答案 1 :(得分:1)
一切都取决于上下文,
this
在某些情况下与您的观点绑定,
举个例子:
var myView = Backbone.View.extend({
events: { "click a" : "myfunction" },
initialize: function(){
_.bindAll(this, 'render', 'myfunction');
},
render: function(){
// rendering data here...
},
myfunction: function(e){
console.log(e.target); // will log the clicked DOM element => <a>
console.log(this); // will log the view => myView
}
});
window.v = new myView({ el : $('#mydiv') });
window.v.render();
如您所见,如果您应该运行此示例,则可以看到this
和e.target
之间的差异。但是,这完全归功于初始化方法中的keyline。
_.bindAll(this, 'methodname', [ methodnames ] );
这在给定方法中的1个时将视图绑定到this
。
如果要从该列表中删除myfunction
,console.log(this);
将记录该元素本身。
但是,您无法从视图中获取数据或功能....
如果将视图绑定到this
,则可以自由选择。
答案 2 :(得分:1)
通过Backbone视图绑定事件,this
将设置为视图本身。这与普通的jQuery不同,其中this
指的是DOM元素
所以在Backbone视图中:
events: { "click a" : "myfunction" },
...
function myfunction(e) {
this // refers to the view
e.target // refers to the element
}
而在普通的jQuery中:
$('a').on('click', myfunction);
...
function myfunction() {
this // refers to the element
e.target // also refers to the element
}
在这两种情况下,您都可以使用e.target
来引用元素