call functions on events NodeJs

Moez Ben Ahmed

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');

         }

     else

         {

         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)

        console.log('good')

}))
Paul Wasson

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) { 
    that.demandConnexion(idZEP)
    console.log('good')
}))

or

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)
});

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related