Using Socket.IO with Backbone.js

March 6th, 2013 by admin Leave a reply »

I work on a lot of different projects, some for work and some for fun and some on the side.  I have been working on a social application here lately that will have lots of topics and within those topics they will have comments.  I felt like the ‘Room’ concept of socket.io would be a good fit for this idea so I began implementing it for this project.  When I first set up socket I was having a problem because stupid me had some javascript that was formatted incorrectly and the engine was not throwing an error with it because it translated to good javascript.  In the meantime while I was doing all of that I had stuck the socket connection in a global variable so it was only making one connection, that does seem to be how you would want your socket.io application to be setup anyways.

I have included the final code below of the solution that is working for me with my backbone views, it turns out I had to create a new socket.io connection each time a topic was clicked on by the user, due to the fact that I am ‘joining’ them to that room, identified by the TopicID.  When I had the socket defined globally, I was getting duplicate messages back to my clients and my only reasoning was that I had the single connection so my clients were getting those dupes back at them.

If you have anything you could throw in for me with input, I would really appreciate it as I think this setup is not a very scalable one, thanks.

//server.js
var io = require('socket.io').listen(server);
io.sockets.on('connection', function(socket) {
  console.log('Socket Connection Made - Server Side');
  socket.on("leaveRoom", function(data){
      console.log('Leaving room ' + data.room);
      socket.leave(data.room);
  });
  socket.on("setRoom", function(data){
      console.log('Joining room ' + data.room);
      socket.join(data.room);
  });

  socket.on('comment', function(data) {
    console.log('Emitting comment');
    socket.broadcast.to(data.room).emit('comment', data.comment);
  });
});

//client.js
//in backbone view initialize()
var url = "http://localhost:3000";
this.socket = io.connect(url);
this.socket.on('connect', function () {
    that.socket.emit("setRoom", {room: that.model.get("TopicId")});
});
this.socket.on('comment', function (data) {
     $('#commentsList').prepend(data);
});

//here is the code to tell server a new comment has been published
that.socket.emit('comment',{ comment: msg, room: that.model.get("TopicId")} );

Advertisement

Leave a Reply