Updating Backbone Collections with Socket.io

Recently a project I worked on required getting backbone to update it's collections when receieving data from a socket.io server. Backbone is designed for RESTful applications, but socket.io does away with RESTful, and instead offers a client side library that will listen for emits (changes) from the server.

For this example lets use a server that recieves and emits messages to and from all connections:

    var io = require('socket.io');

    io.on('connection', function(socket){
        socket.on('message', function(msg){
        socket.emit('message', msg);
      }
    }

One quick and easy way to make them dance together is to reverse the propogation of events and data in backbone from

models->collections->views

to

views->collections->models

Instead of the view listening for changes in its collections and models, we just initialize the view with a socket.io listener, and update our view with the data.

var MessageView = Backbone.View.extend({
  initialize: function(){
    var collection = this.Collection;

    socket.on('chat message', function(msg){
      collection.add({msg: msg});
      collection.render();
    });
});