2016-03-23 15 views
0

実際にイベントの後に関数demandConnexionを呼び出そうとしていますが、それは私のために働いています。「this.demandeConnexionは関数ではありません。どのように私はそれを働かせることができますか?助けてください、これはコードです:イベントの呼び出し関数NodeJs

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

})) 

答えて

2

これは、コールバックが「あなた」のインスタンスではないからです。あなたのケースでは、矢印の機能を使用することです

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

または

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

他のソリューション(私の意見では最高のを)のようなものを試してみてください閉鎖と同じ範囲を維持する

socket.on('connection',()=>{ 
    //here this refers to your Serveur (the enclosing scope) 
}); 
1

thisそれが中に呼び出される関数を指します。あなたはNode.jsのを使用しているとして、あなたはそれが今ではだと思う文脈でthisを使用できるようにするには、矢印の機能を使用するかにthisを設定することができますいずれか関数の外部の変数。

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

それとも

var that = this; 
socket.on('connection', function(idZEP) { that.demandConnexion(idZEP) }); 
関連する問題