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

4

24

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.

Rumor answered 11/7, 2011 at 23:36 Comment(0)
A
26

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.

Aksel answered 13/7, 2011 at 0:35 Comment(0)
C
11

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

It overrides Backbone.sync for you.

Cavalryman answered 6/6, 2012 at 19:55 Comment(1)
Correct link is https://github.com/noveogroup/backbone.iobindObligee
D
8

A much better approach is event-driven architecture using an event aggregator. Great read on the subject is the following Derick Bailey's article => Decoupling Backbone Apps From WebSockets

It keeps stuff highly decoupled, enables easier testing and changing websockets lib, and on top of it all, it doesn't mess up with overriding Backbone's internals like sync()

Downfall answered 17/10, 2012 at 16:16 Comment(0)
T
6

Maybe this excellent tuto will help you: https://blog.andyet.com/2011/02/15/re-using-backbonejs-models-on-the-server-with-node

Tinea answered 20/7, 2011 at 10:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.