Backbone.js:如何将挂起的同步事件排队到服务器?

时间:2013-08-11 19:56:00

标签: javascript backbone.js

我希望基于Backbone.js的网络应用程序能够脱机运行。检测到脱机状态后,如何排队Backbone的同步事件,以便在连接恢复后将它们发送到服务器?

1 个答案:

答案 0 :(得分:1)

您可以使用两种Backbone.sync方法并根据离线/在线状态进行交换:

// Detect sync however you want here
var state = getInternetConnectivityState();

// Save off a local copy of the default Backbone.sync
var ajaxSync = Backbone.sync;

// Create a new Backbone.sync function that works with local storage. I would suggest
// using store.js as it works x-browser, takes care of JSON serialization and is well  
// supported
var localSync = function(method, model, options) {
    if ('GET' === method) {
        model.set('name', store.get(model.id).name);
    }
    ...
}

Backbone.sync = function() {
    if ('offline' === getInternetConnectivityState()) {
        localSync.call(this, arguments);
    }
    else {
        ajaxSync.call(this, arguments);
    }
}