AngryHacker
AngryHacker

Reputation: 61606

How to access "this" scope and a private method in a jquery callback?

Consider the code below. In the click callback I am trying to access the color css property of this. At the same time I need to call a private method setResponsiveClass, which can only be achieved by using this.setResponsiveClass. The code won't compile obviously because this is scoped to event handler.

class SomeClass {
  constructor {    
    $('.someclass').on('click', function() {

      var color = $(this).css('color');
      console.log(color);          

      this.setResponsiveClass();
    });
 }        

  private setResponsiveClass() {
    console.log('hello')
  }
}    

This answer provides ways to achieve either event scoping (by keeping the current code) or class scoping (by converting to a fat arrow syntax).

How can I access both this from the event scope and the private method in the same function?

Upvotes: 0

Views: 93

Answers (1)

user6600549
user6600549

Reputation:

You can trigger this with this way

solution 1.

class SomeClass {
  constructor {    
    $('.someclass').on('click', = () => {

      var color = $(this).css('color');
      console.log(color);          

      this.setResponsiveClass();
    });
 }        

  private setResponsiveClass() {
    console.log('hello')
  }
} 

solution 2.

class SomeClass {
  constructor {    

    var self = this;  <====

    $('.someclass').on('click', function() {

      var color = $(this).css('color');
      console.log(color);          

      self.setResponsiveClass();  <====
    });
 }        

  private setResponsiveClass() {
    console.log('hello')
  }
} 

I hope this helps you 👍

Upvotes: 1

Related Questions