I have a class and I'm relying in the "this" keyword maintaining its class context. However, when I use an event handler within the class, "this" context changes to the event. I know I can eventFunction(){}.bind(this), but I also need the event's 'this' context.
I thought of the following solution "Assigning the class 'this' as a default variable"; it seems to work, but I'm not certain this is the correct appraoch:
class A_Test {
constructor(a, b)
{
this.selector = '.foam_types';
}
bind_foam_type_radios()
{
$(this.selector).on({
mouseenter: this.showFoamTypeExample,
mouseleave: this.hideFoamTypeExample,
click: this.selectFoamType,
}, '.foam_type_option');
}
showFoamTypeExample(e, el = this) // <-- el is being assigned the Class' "THIS"
{
console.log(this); // Event's "this"
console.log(el); // Class' "this"
}
}
var TheTest = A_Test();
TheTest.bind_foam_type_radios();