Swizec Teller - a geek with a hatswizec.com

Senior Mindset Book

Get promoted, earn a bigger salary, work for top companies

Senior Engineer Mindset cover
Learn more

    Elegantly using socket.io in backbone apps

    Backbone.js is my favourite 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 organised is 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.

    Published on December 14th, 2012 in backbone, Client-side JavaScript, jQuery, socket.io, Uncategorized

    Did you enjoy this article?

    Continue reading about Elegantly using socket.io in backbone apps

    Semantically similar articles hand-picked by GPT-4

    Senior Mindset Book

    Get promoted, earn a bigger salary, work for top companies

    Learn more

    Have a burning question that you think I can answer? Hit me up on twitter and I'll do my best.

    Who am I and who do I help? I'm Swizec Teller and I turn coders into engineers with "Raw and honest from the heart!" writing. No bullshit. Real insights into the career and skills of a modern software engineer.

    Want to become a true senior engineer? Take ownership, have autonomy, and be a force multiplier on your team. The Senior Engineer Mindset ebook can help 👉 swizec.com/senior-mindset. These are the shifts in mindset that unlocked my career.

    Curious about Serverless and the modern backend? Check out Serverless Handbook, for frontend engineers 👉 ServerlessHandbook.dev

    Want to Stop copy pasting D3 examples and create data visualizations of your own? Learn how to build scalable dataviz React components your whole team can understand with React for Data Visualization

    Want to get my best emails on JavaScript, React, Serverless, Fullstack Web, or Indie Hacking? Check out swizec.com/collections

    Did someone amazing share this letter with you? Wonderful! You can sign up for my weekly letters for software engineers on their path to greatness, here: swizec.com/blog

    Want to brush up on your modern JavaScript syntax? Check out my interactive cheatsheet: es6cheatsheet.com

    By the way, just in case no one has told you it yet today: I love and appreciate you for who you are ❤️

    Created by Swizec with ❤️