2016-01-01 20 views
2

我正在将我的一个项目转换为使用ES2015,但是当涉及到jQuery的.on事件处理程序时,我遇到了一个问题,要处理'this'关键字自然..jQuery .on事件处理程序和ES2015箭头函数

这里是我的示例代码:

$(".actionBtns").on('click', '.editButton', this.handlerEditBtnClick) //Would give 'this' the value of the button clicked 
 
$(".actionBtns").on('click', '.editButton',() => {this.handlerEditBtnClick()}) //Would give 'this' the value of the class

我不知道我应该重新写在第一行代码上面的使用方式ES2015。

在函数handlerEditBtnClick中,我需要'this'作为类,但我也想访问被单击的按钮。

我的尝试(上面的代码中的第二行)并没有给我访问被点击的按钮DOM元素 - 至少在我看来不能访问它。

感谢,

卢克

编辑 这是handlerEditBtnClick()函数:

handlerEditBtnClicked() { 
 
    var $item = $(this); //This isn't re-written yet, so 'this' actually refers to the edit button that was clicked 
 
    this.editItem($item); //This is where I need 'this' to be the class 
 
}

你可以看到,我需要 '这个' 来是两个不同的东西..我不完全确定如何从handlerEditBtnClick内this.editItem()以外调用editItem函数;

请注意,名字只是通用名称,以方便在$(".actionBtns").on('click', '.editButton',() => {this.handlerEditBtnClick()}) handlerEditBtnClick功能打字

+0

我想重写的原因是因为我想'this'是该函数所在的类。 我将用更多的代码更新我的问题,以说明为什么我想要这样做 – Denno

回答

2

在diffarent环境中称之为(this指的是类),
因为()=>{}相当于function(){}.bind(this)所以你可以做任何

$(".actionBtns").on('click', '.editButton',() => {this.handlerEditBtnClick()})

$(".actionBtns").on('click', '.editButton', this.handlerEditBtnClick.bind(this))

然后访问被点击,你可以随时使用e.target
(或e.currentTarget根据您的需要)

function handlerEditBtnClick(e) { 
console.log(e.target); // button that was clicked 
} 
+0

啊事件目标!当然。感谢Bek! – Denno

+0

不用担心@ user1560593 :) – Bek

+0

Geez是我的名字..猜猜我应该弄清楚如何更新.. – Denno

0

按钮你也能做到这样(是的,在ES5语法):

$('.element').click(function(){ 
    $(this)===$('.element') //true 
}); 

显然这是因为jQuery cann ot绑定选择器在写入“箭头方式”时(在转换为ES6之后)发挥作用。

检查我自己的一些具体情况,或只使用event.target

相关问题