Skip to content

Instantly share code, notes, and snippets.

@tiagoa
Created October 13, 2012 23:34
Show Gist options
  • Star 23 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save tiagoa/3886606 to your computer and use it in GitHub Desktop.
Save tiagoa/3886606 to your computer and use it in GitHub Desktop.
Overwrite Backbone.sync method to persist model via WebSocket
// Inspired by https://github.com/logicalparadox/backbone.iobind/blob/master/lib/sync.js
// Overwrite Backbone.sync method
Backbone.sync = function(method, model, options){
// create a connection to the server
var ws = new WebSocket('ws://127.0.0.1:1234');
// send the command in url only if the connection is opened
// command attribute is used in server-side.
ws.onopen = function(){
// in my convention, every message sent to the server must be:
// {"command":"action", "data":"data sent to the server"}
ws.send(JSON.stringify({"command":model.url, data:model.attributes}));
};
ws.onmessage = function(message){
// message.data is a property sent by the server
// change it to suit your needs
var return = JSON.parse(message.data);
// executes the success callback when receive a message from the server
options.success(return);
};
};
@bluurn
Copy link

bluurn commented May 29, 2014

nice

@Industrial
Copy link

WHOA!!

Found this through google.

This is not the correct way to handle this. You should not create a new websocket connection every time any model changes, rather, only the sending and receiving part.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment