Moez Ben Ahmed
Moez Ben Ahmed

Reputation: 93

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

         }

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

}))

Upvotes: 0

Views: 48

Answers (2)

Paul Wasson
Paul Wasson

Reputation: 46

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

Upvotes: 2

baao
baao

Reputation: 73211

this refers to the function it is called in. As you are using node.js, you could either use an arrow function to make this available in the context you think it's in now, or set this to a variable outside of the function.

socket.on('connection', idZEP => this.demandConnexion(idZEP))

Or

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

Upvotes: 1

Related Questions