Created
October 13, 2012 23:34
-
-
Save tiagoa/3886606 to your computer and use it in GitHub Desktop.
Overwrite Backbone.sync method to persist model via WebSocket
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.