0

Please find the below this reference fails when I hit a method via route

say /api/certifications it inturn calls indexAction and i try to call the property say using this.collection and it gives error as undefined. any one pls help.

var baseController = require('../../../common/basecontroller');
var inherits       = require('util').inherits;
var certificationModel  = require('../models/certification');

//Certification constructor
var Certification = function() {
    Certification.super_.call(this);
    this.collection = 'certification';
    this.data       = {};
    this.cond       = {};
    this.proj       = {};
};

inherits(Certification, baseController);

Certification.prototype = {
    /*
    **   To retrieve all the countries.
    **/
    indexAction: function(req, res) {       
        certificationModel
        .readQuery(req.app.locals.db, that.collection, that.cond, that.proj)
        .then(function(results) {
        return req.app.sendApiResponse('200', 'success', '', results, res);
        })
        .catch(function(err) {
        return req.app.sendApiResponse('1007', 'error', req.app.resCode['1007'], 'Failed to process your request', res);
        });
    }

};

var certificationObj = new Certification();
var that = certificationObj;

module.exports = certificationObj;
/* End of Certification Module */

/* Certification Route */
var certificationInstance = require('../controllers/certification');

module.exports = function(router) { 
//Country
router
.route("/certifications")
.get(certificationInstance.indexAction);
};

I have done it creating the object and assign to that variable.

var certificationObj = new Certification();
var that = certificationObj;
Sandeep Sukhija
  • 1,156
  • 16
  • 30
Sethu
  • 195
  • 1
  • 8
  • I don't see any `this` in your code? – Bergi Jun 09 '16 at 15:53
  • In the indexAction method can't able to access the public property declared in the constructor via this.collection. when i print in console it shows 'undefined' – Sethu Jun 10 '16 at 05:51
  • Is that why you're trying to use `that`? Not going to work without initialising `var that` anywhere. – Bergi Jun 10 '16 at 09:45
  • `.get(certificationInstance.indexAction);` is the problem, you'll need to do `.get(certificationInstance.indexAction.bind(certificationInstance));` – Bergi Jun 10 '16 at 09:46
  • Thanks, it's working now. – Sethu Jun 10 '16 at 11:01

1 Answers1

0

Use Certification.prototype.indexAction = ... instead of Certification.prototype = {indexAction: ...} not to loose the original prototype object.

Pavel Gatnar
  • 3,987
  • 2
  • 19
  • 29