Skip to content
Advertisement

use “this” in a function passed to eventListener

Hello people I was refactoring some code and couldn’t figure a way to reuse the ‘this’:

a/ Code I have

someElement.addEventListener('click', function (event){
  
   if( this.nextSibling.classList.contains('expanded') ){
       event.target.closest('.hello').getElementsByClassName('expanded')[0].classList.remove('expanded')
   }
});

b/ I want to move the function to another file and export it as:

export function doStuff(){ 
       if( this.nextSibling.classList.contains('expanded') ){
           event.target.closest('.hello').getElementsByClassName('expanded')[0].classList.remove('expanded')
       }
 }

and use it like:

import {doStuff} from 'somePath'
    
someElement.addEventListener('click', doStuff)

but ‘this’ is undefined.. how do I bind it?

Advertisement

Answer

Pass this as parameter to function (and also decouple from event too):

someElement.addEventListener('click', function (event){
   doStuff(this, event.target);
});

export function doStuff(element, target){ 
       if(element.nextSibling.classList.contains('expanded') ){
           target.closest('.hello').getElementsByClassName('expanded')[0].classList.remove('expanded')
       }
 }
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement