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