Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use backbone.js with websockets/socket-io/nowjs

Tags:

I am just getting into backbone.js and am finding progress a little slow. My main problem is working out how to keep my client and server side models in sync using socket-io (technically I am using now.js but the same principal should apply).

I think the best way is to override the sync method but some simple advice would be really welcome.

like image 473
henry.oswald Avatar asked Jul 11 '11 23:07

henry.oswald


People also ask

How do I connect a Socket.IO to a WebSocket?

@Mobilpadde You can see it yourself: open socket.io/demos/chat in Chrome, in F12 > network, filter with "EIO=3&transport=websocket", there should be some of them, and the response headers should contain "Connection:upgrade", and there should be "Frames" tab in detail panel, instead of "Preview" and "Response" tabs for ...

Does Socket.IO use WebSocket?

Although Socket.IO indeed uses WebSocket for transport when possible, it adds additional metadata to each packet. That is why a WebSocket client will not be able to successfully connect to a Socket.IO server, and a Socket.IO client will not be able to connect to a plain WebSocket server either.

How does Backbone JS work?

BackboneJS provides various building blocks such as models, views, events, routers and collections for assembling the client side web applications. When a model changes, it automatically updates the HTML of your application. BackboneJS is a simple library that helps in separating business and user interface logic.


2 Answers

Simply overwrite Backbone.sync so that it sends messages down socket.io and tells the relevant backbonejs models on the server to alter state.

The interesting part of this solution is setting up the master-master relationship. You need to insure that for any client they can only "update" the state of models on the server that they have "ownership" of to avoid hackers and server-side state corruption.

So for each client they have a set M where that client is the master of all models in M and has a set S where that client has slaves of all the models in S.

It can only force updating on the server of models in M and only one client should have a particular model in M (or you need to implement a solid locking / merging implementation).

Whenever a model on the server is updated you simply push out to any client who has that model in S. (and push to any client who has that model in M if the model is in M for multiple clients).

A lot of thought needs to go into control / permissions and ownership that is normally handled by the MVC controller once a client POST/PUT/DELETE some data.

like image 164
Raynos Avatar answered Feb 11 '23 16:02

Raynos


Check out backbone.iobind: https://github.com/noveogroup/backbone.iobind

It overrides Backbone.sync for you.

like image 35
Evan Moran Avatar answered Feb 11 '23 17:02

Evan Moran