0

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?

AngryHacker
  • 59,598
  • 102
  • 325
  • 594

1 Answers1

1

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

George C.
  • 6,574
  • 12
  • 55
  • 80
  • Solution 1 doesn't work because because the TypeScript compiler redefines this as _this=this. Solution 2 does work, but we are basically back to JavaScript tricks. I was hoping TypeScript would have a more elegant solution to this problem. – AngryHacker Mar 27 '19 at 18:22