Few days ago I spent almost 30min figuring out
what on earth was wrong this event toggleClass
,hasClass
,$(this)
.
As the code seem to be fine.
$(".s_nav_menu").on('click', ()=> {
if( $(this).parent().next('div').hasClass('p_t_tap_inner')){
$(this).parent().toggleClass( "on" );
}
});
after checking the debug tools, I realized the if statement returns false.
This is not because the p_t_tap_inner
does not exist. It was because
the $(this)
selector was always null.
So, I realized the JQUERY ARROW FUNCTION
executes differently.
if( $(this).parent().next('div').hasClass('p_t_tap_inner'));
It Works
So after changing the arrow function,It works. I was surprised to dig why ? that happens
$(".s_nav_menu").on('click',function () {
if( $(this).parent().next('div').hasClass('p_t_tap_inner')){
$(this).parent().toggleClass( "on" );
}
});
Findings
No Solution? Nahhh
No solution
because the arrow function is already bound when it is created this Later, it cannot be rebounded at execution time. stayJQueryIn general, arrow functions are not used becauseJQueryMany times a callback function is dynamically bound this So you don’t want to bind it when you create it this And don’t use arrow functions.
Solution 😀
I found out in using the this
keyword in a callback it is true that it does not rebound after execution.But
we can get the current Event target and use that as our INSTANCE
of this
.
Event binding
$button.on('click', (e) => {
var $this = $(e.currentTarget);
// ... deal with $this
});
Loop
Array.prototype.forEach.call($items, (el, index, obj) => {
var $this = $(el);
// ... deal with $this
});
JUST DONT USE ARROW FUNCTIONS
// Go from this code:
$('.cta').on('click',function() {
var that = this;
setTimeout(function() {
$(that).toggleClass('on');
}, 1000)
});
// To this code:
$('.cta').on('click',function() {
setTimeout(()=> {
$(this).toggleClass('on');
}, 1000)
});
Summary ✺
ES6 this
Keyword in jQuery Call back arrow functions executes different.
And is usually good to still with the normal function calls than using arrow keys.If arrow keys are
really needed then always do not forget to get the event target element and execute actions
on them.
Refs
wesbos |
---|
stackoverflow |
'Javascript' 카테고리의 다른 글
What is Jest and How to use it in testing? (0) | 2022.10.08 |
---|