I seem to be in a catch-22 right now, where I want to attach an event listener within a javascript/typescript object (and retain access to this
in my callback function), but I need to remove said event listener as well. Normally, setting up such a callback (where one has access to this
) uses anonymous functions, e.g.:
class MyClass {
property = 'testing...';
constructor(public element: HTMLElement) {}
attachListener() {
this.element.addEventListener(
'mouseover',
() => { console.log(this.property); }
);
}
removeListener() {
this.element.removeEventListener(
'mouseover',
PROBLEM!
)
}
}
Obviously this wont work, as my callback is anonymous, thus I don't have the ability to remove it. In my case, this would be the only mouseover
event, so I'd be fine with removing all attached listeners, but haven't found a way to do that either. Any thoughts on the best way to approach this?