'this' is undefined for EventController handler

This is what I’m trying to do

  ionViewWillEnter() {
    this.events.subscribe('new-data', this.doStuff)
  }

  ionViewWillLeave() {
    this.events.unsubscribe('new-data', this.doStuff)
  }

  doStuff() { 
    this.data = this.dataProvider.get(); // error here - 'this' is undefined
  }

Error: Uncaught (in promise): TypeError: Cannot read property ‘dataProvider’ of undefined

How can I access this class from my event handler function?
(If I use arrow function, instead of passing this.doStuff, then it there is no error, but I cannot unsubscribe)

Yes you can. Something like this.

1 Like