我試圖重寫默認的Backbone.sync函數與一個同步通過WebSockets。到目前爲止,我已經成功地使用下面的代碼發送一個獲取請求到服務器,但我不知道如何捕獲響應。Backbone.js同步使用本機websockets
我見過人們建議每次都重置套接字onmessage事件處理程序,但我不禁認爲這可能會導致響應不同步,如果一次請求很多數據(如果一個請求需要很長時間才能響應)。
是否有任何如何實現我想要做的事情的例子?
var app = app || {};
function fnSync (sMethod, oModel, oOptions) {
var bSuccess,
sResponse;
bSuccess = false;
switch (sMethod) {
case "read":
if (oModel.id !== undefined) {
app.socket.send(JSON.stringify({
"method": "get",
"url": oModel.url,
"id": oModel.get("_id")
}));
} else {
app.socket.send(JSON.stringify({
"method": "get",
"url": oModel.url
}));
}
bSuccess = true;
break;
default:
throw "Backbone.sync doesn't know how to " + sMethod;
bSuccess = false;
break;
}
(bSuccess) ? oOptions.success() : oOptions.error();
}
(function() {
app.socket = new WebSocket("ws://localhost:3001");
app.socket.onopen = function() {
Backbone.sync = fnSync;
app.router = new app.Router();
Backbone.history.start();
}
app.socket.onmessage = function (oMessage) {
//console.log("Socket message", oMessage.data);
}
})();