Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery .on event handler and ES2015 arrow function

I'm converting a project of mine to use ES2015, but I've run into a problem when it comes to jQuery's .on event handler, to do with the 'this' keyword naturally..

Here is my example code:

$(".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

I'm not sure the way I'm supposed to re-write the first line in the code above to use ES2015.

In the function handlerEditBtnClick, I need 'this' to be the class, but I also want access to the button that was clicked.

My attempt (the second line in the code above), doesn't give me access to the button DOM element that was clicked - at least in no way that I can think of accessing it.

Thanks,

Luke

Edit This is the handlerEditBtnClick() function:

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
}

You can see where I need 'this' to be two different things.. I'm not entirely sure how to call the editItem function from within handlerEditBtnClick other than this.editItem();

Please note the names are just generic names, for ease of typing

like image 866
Denno Avatar asked May 07 '26 02:05

Denno


2 Answers

in $(".actionBtns").on('click', '.editButton', () => {this.handlerEditBtnClick()}) handlerEditBtnClick function is called in diffarent context (this refers to class),
because ()=>{} is equivalent to function(){}.bind(this) so you can do either

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

or

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

then to access the button that was clicked you can always use e.target
(or e.currentTarget depending on your needs)

function handlerEditBtnClick(e) {
 console.log(e.target); // button that was clicked
}
like image 69
Bek Avatar answered May 08 '26 17:05

Bek


You can also do it this way (yes, in ES5 syntax):

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

Propably it is because jQuery cannot bind selector to function when it is written "arrow way" (after translate to ES6).

Checked myself on few specific cases, or just use event.target.

like image 27
Michał Wojas Avatar answered May 08 '26 16:05

Michał Wojas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!