Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

controller as class: this is undefined! #29

Closed
joneldiablo opened this issue Oct 15, 2018 · 5 comments
Closed

controller as class: this is undefined! #29

joneldiablo opened this issue Oct 15, 2018 · 5 comments

Comments

@joneldiablo
Copy link

using my controller as class the this is undefined!!

@joneldiablo
Copy link
Author

joneldiablo commented Oct 15, 2018

/**
 * @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
Copy link
Owner

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
Copy link
Author

joneldiablo commented Oct 16, 2018

"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
Copy link
Owner

Alright, thanks for posting the solution 👍

I will close this issue for now.

@joneldiablo
Copy link
Author

#32

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants