Swizec Teller - a geek with a hatswizec.com

    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.

    Events

    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.button_clicked();
    });

    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) {
    that.got_message(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 () {
    this.__initialize();
    },
    __initialize: function () {
    if (this.socket_events && _.size(this.socket_events) > 0) {
    this.delegateSocketEvents(this.socket_events);
    }
    },
    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.

    Enhanced by Zemanta

    Did you enjoy this article?

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

    Learned something new?
    Read more Software Engineering Lessons from Production

    I write articles with real insight into the career and skills of a modern software engineer. "Raw and honest from the heart!" as one reader described them. Fueled by lessons learned over 20 years of building production code for side-projects, small businesses, and hyper growth startups. Both successful and not.

    Subscribe below 👇

    Software Engineering Lessons from Production

    Join Swizec's Newsletter and get insightful emails 💌 on mindsets, tactics, and technical skills for your career. Real lessons from building production software. No bullshit.

    "Man, love your simple writing! Yours is the only newsletter I open and only blog that I give a fuck to read & scroll till the end. And wow always take away lessons with me. Inspiring! And very relatable. 👌"

    ~ Ashish Kumar

    Join 15,883+ engineers learning lessons from my "raw and honest from the heart" emails.

    ⭐️⭐️⭐️⭐️✨
    4.5 stars average rating

    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

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

    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 ❤️