aichbauer / express-routes-mapper

a small mapper for express routes
MIT License
21 stars 16 forks source link

controller as class: this is undefined! #29

Closed joneldiablo closed 6 years ago

joneldiablo commented 6 years ago

using my controller as class the this is undefined!!

joneldiablo commented 6 years ago
/**
 * @class UserController
 */
class UserController extends Controller {
  constructor() {
    super(User, ['firstname', 'lastname', 'socialSecurityNumber', 'birthdate', 'email']);
  }
....
}
/**
 * @class Controller
 */
class Controller {
  constructor(model, qcolumns) {
    this.model = model;
    this.qcolumns = qcolumns;
  }
  get(req, res) {
    let status = 200;
    let response = {
      success: true
    }
    let query = req.params.q || '';

    console.log(typeof this);
}
aichbauer commented 6 years ago

Could you please create a repository where you reproduce this issue?

Which version of express-routes-mapper are you using? Which node version are you using? How does your routes file look like?

joneldiablo commented 6 years ago

"express-routes-mapper": "^1.0.4", I think the problem comes from express, the solution was to bind the "this" in the constructor:

constructor(model, qcolumns) {
    this.model = model.query();
    this.qcolumns = qcolumns;
    //PATCH: _this_ is undefined using express and express-routes-mapper
    this.get = this.get.bind(this);
    this.set = this.set.bind(this);
    this.getByID = this.getByID.bind(this);
    this.update = this.update.bind(this);
    this.delete = this.delete.bind(this);
  }

image

image

aichbauer commented 6 years ago

Alright, thanks for posting the solution 👍

I will close this issue for now.

joneldiablo commented 5 years ago

32