Reputation: 61606
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
Reputation:
You can trigger this with this way
class SomeClass {
constructor {
$('.someclass').on('click', = () => {
var color = $(this).css('color');
console.log(color);
this.setResponsiveClass();
});
}
private setResponsiveClass() {
console.log('hello')
}
}
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