0

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?

MarkD
  • 4,864
  • 5
  • 36
  • 67

1 Answers1

2

Instead of an anonymous function make the handler a class method

class MyClass {
  property = 'testing...';

  constructor(public element: HTMLElement) {
     this.handleMouseOver = this.handleMouseOver.bind(this)
  }


  handleMouseOver(event) {
    console.log(this.property)
  }

  attachListener() {
    this.element.addEventListener(
      'mouseover',
      this.handleMouseOver
    );
  }

  removeListener() {
    this.element.removeEventListener(
      'mouseover',
      this.handleMouseOver
    )
  }
}
charlietfl
  • 170,828
  • 13
  • 121
  • 150
  • Thanks! It appears I was over thinking things (though I swear I had an issue in the past with passing the class method directly to an event listener). In my actual code I was simply using the anonymous function to call `this.someMethod()` so this worked great! – MarkD Nov 17 '18 at 17:27
  • 1
    Ahh... probably have to put `this.handleMouseOver = this.handleMouseOver.bind(this)` in constructor. Will update in answer – charlietfl Nov 17 '18 at 17:29
  • Now the `console.log(this.property)` does not work any more – Bergi Nov 17 '18 at 17:29