0

actually i'm trying to call a function which is created in another "class", and i want to use is in the socket.on (...) but it is not working , it keeps showing

this.function is not a function.

here is the code :

//calling the function 
    Serveur.prototype.traitementSurConnection = function(socket) {
var that = this
    socket.on('connection', function (creator, typeArtifact,idConteneur, typeConteneur) {

        that.addArtifact('momo', 'img', 1,0);

    })
};

//the function

ZoneCollaborative.prototype.addArtifact = function(creator, typeArtifact,idConteneur, typeConteneur) {

    // calcul d'un nouvel identifiant

    var id = this.setIdAr();

    console.log('    *** ZC : calcul nouveau IdArtifact = '+id);


    // création de l'artifact

    var monArtifact = new Artifact(id, creator, typeArtifact, idConteneur,

            typeConteneur);

    console.log('    *** ZC : creation artifact'+monArtifact.getId() );

    // ajout à la liste

    this.artifacts.push(monArtifact);


    console.log('    *** ZC : total artifact ='+ this.artifacts.length);

};

1 Answers1

0

In the context of socket.on(), this refers not to the function/object containing the socket.on() call, but rather the socket which is calling the on function. This is typically how people would handle this problem:

var self = this;
socket.on('connection', function (creator, typeArtifact,idConteneur, typeConteneur) {

    self.addArtifact('momo', 'img', 1,0);

})

This is a common issue in JavaScript code, the this keyword is very dependent on the scope in which it's being used and so you often see this pattern being used to preserve a this into a new scope.

Here is a related SO post that has some additional information on this: What underlies this JavaScript idiom: var self = this?

Community
  • 1
  • 1
CodingGorilla
  • 18,826
  • 2
  • 41
  • 61