Moez Ben Ahmed Moez Ben Ahmed - 3 years ago 282
Node.js Question

call functions on events NodeJs

actually i'm trying to call the function demandConnexion after an event, but it is working for me , it telles me that "this.demandeConnexion is not a function" . how can i get it to work ? help , this is the code :

Serveur.prototype.demandConnexion = function(idZEP) {

if (this.ZP.createZE(idZEP))


console.log(' ==> socket : demande de creation ZE pour '+idZEP +' accepte');




console.log(' ==> socket : demande de creation ZE pour '+idZEP +' refuse');


Serveur.prototype.traitementSurConnection = function(socket) {

// console.log('connexion');

console.log(' ==> socket connexion');

// traitement de l'evenement DEMANDE DE CONNEXION D'UNE ZE

socket.on('connection', (function(idZEP) { this.demandConnexion(idZEP)



Answer Source

It's because when the callback is called "this" isn't your "Serveur" instance. In your case try something like

var that = this;
socket.on('connection', (function(idZEP) { 


socket.on('connection', this.demandConnexion.bind(this));

An other solution (the best in my opinion) would be to use the arrow functions to keep the same scope as the closure

socket.on('connection', ()=>{
  //here this refers to your Serveur (the enclosing scope)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download