DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Elegantly Using Socket.io in Backbone Apps

Swizec Teller user avatar by
Swizec Teller
·
Dec. 23, 12 · Interview
Like (1)
Save
Tweet
Share
2.97K Views

Join the DZone community and get the full member experience.

Join For Free

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.


app Socket.IO Event

Published at DZone with permission of Swizec Teller, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Beginners’ Guide to Run a Linux Server Securely
  • Why Open Source Is Much More Than Just a Free Tier
  • Kotlin Is More Fun Than Java And This Is a Big Deal
  • Why You Should Automate Code Reviews

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: