1

I have added a click event handler on a particular template like this:

let tableFilter = this.template.querySelector('.' + strDataTableTargetId + '_filter');
tableFilter.addEventListener('click',  this.handleCustomFilterEvents);

handleCustomFilterEvents(objEvent){
    if (objEvent !== undefined && objEvent !== null && objEvent.target !== undefined && objEvent.target !== null &&
        objEvent.target.classList !== undefined && objEvent.target.classList !== null){
        if(objEvent.target.classList.contains('addFilterAnchor')){
            this.addFilterRow(this.strTableClass); //Not able to access addFilterRow method
        }
    }
}

But still I am not able to access addFilterRow method.

I tried accessing like this :

tableFilter.addEventListener('click',  () => this.handleCustomFilterEvents);

But then the handler isn't even getting invoked.

Any thing I am missing?

Update (Answer)

I forgot to pass event, that is why it was not working with => This works:

tableFilter.addEventListener('click', (event) => this.handleCustomFilterEvents(event));

3
  • Before this.addFilterRow(this.strTableClass); can you check if objEvent.target.classList exist and then contains addFilterAnchor?
    – Klecool
    May 30, 2020 at 8:20
  • Yes its available, basically I think its context changes that is why I am not able to access, but even after trying with empty constructor it does not work. May 30, 2020 at 8:22
  • Git it : tableFilter.addEventListener('click', (event) => this.handleCustomFilterEvents(event)); May 30, 2020 at 8:24

2 Answers 2

1

I forgot to pass event, that is why it was not working with => This works:

tableFilter.addEventListener('click',  (event) => this.handleCustomFilterEvents(event));


handleCustomFilterEvents(objEvent){
    if (objEvent !== undefined && objEvent !== null && objEvent.target !== undefined && objEvent.target !== null &&
        objEvent.target.classList !== undefined && objEvent.target.classList !== null){
        if(objEvent.target.classList.contains('addFilterAnchor')){
            this.addFilterRow(this.strTableClass); //Here I am able to access addFilterRow method
        }
    }
}
1
  • In my opinion, this is the best answer -- just use an arrow function, and you can call any other functions/methods in the class with the key word "this" INSIDE that arrow function. Jun 5 at 21:35
0

Basic problem with your code is the function call doesn't get context of this properly.

tableFilter.addEventListener('click',  () => this.handleCustomFilterEvents);

Apart from fat arrow function, you can use bind function to pass the context of this:

tableFilter.addEventListener('click',  this.handleCustomFilterEvents.bind(this));
1

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .