Over a million developers have joined DZone.

Elegantly using socket.io in backbone apps

DZone's Guide to

Elegantly using socket.io in backbone apps

· Web Dev Zone ·
Free Resource

A true open source, API-first CMS — giving you the power to think outside the webpage. Try it for free.

Backbone.js is my favorite modern MVC framework for client-side javascript. Not that I’ve seriously tried any others … simply didn’t feel the need to.

The way apps are usually organized in Backbone is that data is king. A view reacts to some user action and changes some data in a model. Everybody who’s listening for that change then reacts and does something either to their view (adding something new on the screen, say) or data gets changed. Sometimes a change in data will cause the browser URL to change.

Whatever, the important part is events are usually communicated through state changes.


Despite the god-like status of models, most of your code goes into views. That’s where you have to react to two types of events:

  • data changes
  • user actions

Listening to data changes is easiest done in the initialize function, something like so:

    initialize: function () {
        this.model.on("change", this.render, this);

Okay, but what about user actions? Like somebody clicking on a button or entering a specific form field? Well, you could do it the old jQuery way everyone’s come to love by now.

        var that = this;
        this.$el.find('a.button', function () {

That can get unwieldy real quick … Backbone has us covered with the events hash:

    events: {
        "click a.button": "button_clicked"

Both of these approaches result in this.button_clicked being called when a user clicks the button. Except the second approach is much easier on the eye and significantly less convoluted when you have ten different events doing things.

But what happens when you add socket.io to the mix?

Adding socket.io

Backbone doesn’t have any built-in support for a third source of events so you end up doing things the old way again. Adding listeners to a global socket in your initialize function. Global sockets might sound like a bad idea, but I find having a single socket communicating with the server to make things easier.

I usually keep the socket in the global App object.

But this feels dirty:

        window.app.socket.on("message", function(message) {

Or worse, handling everything about the message in the callback!

Instead, I started making all my views extend a common MainView that enables me to listen for socket events just like I would for user actions:

var MyView = MainView.extend({
    socket_events: {
        "message": "got_message"

MainView then takes care of binding socket events to their callbacks much in the same way as Backbone’s native View does.

var MainView = Backbone.View.extend({
    initialize: function () {
    __initialize: function () {
        if (this.socket_events && _.size(this.socket_events) > 0) {
    delegateSocketEvents: function (events) {
        for (var key in events) {
            var method = events[key];
            if (!_.isFunction(method)) {
                method = this[events[key]];
            if (!method) {
                throw new Error('Method "' + events[key] + '" does not exist');
            method = _.bind(method, this);
            window.app.socket.on(key, method);

The reason there’s two initialize functions is that we can’t properly hook into the default View object and add some functionality. So we use initialize to do event delegation when the object is created – backbone calls initialize from the constructor – but if a child view needs their own initialize function, they should still be able to delegate socket events.

Such a child view would simply call this.__initialize() to execute MainView’s initialize function and get things working.

This is far from perfect and to get all of this really working the way I’d like – as seamlessly as user actions – I would have to make a pull request to Backbone … but it’s a good start to elegantly using socket.io in backbone apps.

The New Standard for a Hybrid CMS: GraphQL Support, Scripting as a Service, SPA Support. Watch on-demand now.


Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}