0

My Hapi route calls my handler handler: myController.get which is defined as

const myController = new MyController();

and MyController just extends BaseController as we see below

export class MyController extends BaseController<MyClass> {

  constructor () {
    super(new MyDataAccess());
  }
}

with BaseController being

export class BaseController<T> {
  constructor(protected dataAccess: BaseDataAccess<T>) { }

  public async getAll(request, reply) {
    console.log('BaseController this', this);

Oddly enough, this prints out as 'undefined', which doesn't make any sense because I have already instantiated myController in the route file, which should've kicked off a new instance of BaseController for this to invoke, right?

Question How can I access an instance of MyController from a Hapi route handler?

Joshua Ohana
  • 5,613
  • 12
  • 56
  • 112
  • Possible duplicate of [How to access the correct \`this\` inside a callback?](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) – CRice Oct 31 '18 at 23:09
  • 1
    In this case, I would bind the method to its instance. EG: `handler: myController.get.bind(myController)` – CRice Oct 31 '18 at 23:10
  • @CRice I read that post first and I it didn't seem to help my issue – Joshua Ohana Oct 31 '18 at 23:15
  • @CRice Magic! (the bind that is), thanks a bunch, if you mark that as an Answer I'll accept – Joshua Ohana Oct 31 '18 at 23:19

1 Answers1

0

In order to fix I just had to .bind the controller to preserve the 'this' context

handler: myController.get.bind(myController)

Courtesy of CRice from the comments above, "In this case, I would bind the method to its instance. EG: handler: myController.get.bind(myController)" – CRice Oct 31 at 23:10

Joshua Ohana
  • 5,613
  • 12
  • 56
  • 112