0

I want socket io to send an array to the client side. This is successful when the user first signs in, however when the user signs out and then sign back in, socket io sends out two of the same array. I can't seem to figure out why it does this. here is my code server side:

var object = [];
  query.find({
    success: function(results){
      for(var i=0; i< results.length; i++){
        var file = results[i].toJSON();
        for(var k in file){
          if (k ==="javaFile"){
            for(var t in file[k]){
               if (t === "name"){
                  temp = file[k][t];
                  var getname = temp.split("-").pop();
                  object[i] = getname;

               }                  
            }
          }
        }
      }
    }
  });

io.on('connection', function(socket){
    socket.emit("FileName", object);
     console.log(object);
  });

this is my client side:

socket.on('FileName', function(data){
var name = JSON.stringify(data);
console.log(data);
 clients[socket.id] = socket;
Suji
  • 767
  • 3
  • 12
  • 28
  • you are not unsubscribing to the socket when you log out. so your socket.on('FileName') is registered twice. – Pogrindis May 14 '15 at 13:14

1 Answers1

0

When you are logging out make sure you unsubscribe from the listeners.

Something like this should work :

socket.removeAllListeners("FileName");

Alternatively you can unsub like so :

socket.removeListener("FileName");

Ref : Google Groups Discussion

This means the next time you come along and login there is only 1 subscription to emit to.

Related Question

Community
  • 1
  • 1
Pogrindis
  • 7,755
  • 5
  • 31
  • 44
  • I can't seem to get it to work. I get `TypeError: listener must be a function`. In my routes under signout I wrote `io.on('disconnect', function(socket){socket.removeAllListener('FileName')});` – Suji May 14 '15 at 21:36
  • @wisemen its `socket.removeAllListeners` you are missing an S at the end – Pogrindis May 15 '15 at 08:36
  • I tried that too, it doesn't work. socket.removeAllListeners, I don't get any error message, however it doesn't remove the listener. – Suji May 15 '15 at 15:16