Hello people I was refactoring some code and couldn’t figure a way to reuse the ‘this’:
a/ Code I have
JavaScript
x
7
1
someElement.addEventListener('click', function (event){
2
3
if( this.nextSibling.classList.contains('expanded') ){
4
event.target.closest('.hello').getElementsByClassName('expanded')[0].classList.remove('expanded')
5
}
6
});
7
b/ I want to move the function to another file and export it as:
JavaScript
1
6
1
export function doStuff(){
2
if( this.nextSibling.classList.contains('expanded') ){
3
event.target.closest('.hello').getElementsByClassName('expanded')[0].classList.remove('expanded')
4
}
5
}
6
and use it like:
JavaScript
1
4
1
import {doStuff} from 'somePath'
2
3
someElement.addEventListener('click', doStuff)
4
but ‘this’ is undefined.. how do I bind it?
Advertisement
Answer
Pass this
as parameter to function (and also decouple from event
too):
JavaScript
1
10
10
1
someElement.addEventListener('click', function (event){
2
doStuff(this, event.target);
3
});
4
5
export function doStuff(element, target){
6
if(element.nextSibling.classList.contains('expanded') ){
7
target.closest('.hello').getElementsByClassName('expanded')[0].classList.remove('expanded')
8
}
9
}
10