Monday, July 8, 2013

Connecting Socket.io to Backbone.js

I've been messing around with Backbone.js recently, and as a learning project I started work on the beerNode client this past weekend. One of the problems that needed to be solved is how to "connect" socket.io events to the Backbone model for that device. Backbone has a very nice event mechanism that connects models to views, but there is no mechanism (that I know of) to send an event to all models in a collection.

I solved that problem as such:

  • Create a global object that is extended from Backbone.Events
  • Add that object to the Backbone.Model prototype
  • During model init, listen to 'change' events from the global event object
  • When a device status update comes in, trigger the global object with the device object. The models will get the event and will check if the event is for the device being controlled.

Create the global event aggregator, assign it to the Backbone.Model prototype and listen for io events:
A device status update has come in from our socket.io server - trigger the global object, passing the device object as the parameter:
Done. Socket.io events are are now distributed to the various Backbone models without any direct coupling. Perfect.

No comments:

Post a Comment