0

我有一个从 URL 获取数据的集合。

BarCollection = Backbone.Collection.extend({
  model: BarModel,
  url: // Some URL
});

但问题是我不仅想从 URL 获取数据,还想从本地存储获取数据。我希望我能做这样的事情:

BarCollection = Backbone.Collection.extend({
  model: BarModel,
  url: // Some URL,
  localStorage: new Backbone.LocalStorage('bars')
});

但是.fetch()方法不能同时从 url 和本地存储中获取数据。

简单的解决方法是创建两个不同的集合:一个用于 URL,一个用于本地存储。获取后合并它们。

BarCollection = Backbone.Collection.extend({
  model: BarModel,
  url: // Some URL
});

LocalBarCollection = Backbone.Collection.extend({
  model: BarModel,
  localStorage: new Backbone.LocalStorage('local-contributors')
});

我想知道是否有更漂亮的方法来做到这一点。

4

1 回答 1

0

要使任何集合或模型能够从本地存储和服务器同步,可以覆盖 Backbone 的同步功能:

Backbone.sync = (function(sync) {
    return function(method, model, options) {
        options = options || {};
        var key = _.result(model, 'localStorage'),
            response;

        // if the localStorage property exist on the model/collection
        // first try to sync with the localStorage
        if (key) {
            switch (method) {
                case 'create':
                case 'update':
                    var data = model.toJSON(),
                        text = JSON.stringify(data);
                    localStorage.setItem(key, text);
                    break;
                case 'delete':
                    localStorage.removeItem(key);
                    break;
                case 'read':
                    response = JSON.parse(localStorage.getItem(key));
                    if (response) model.set(response, { parse: true });
                    break;
            }
        }

        // then, always sync with the server as it normally would
        return sync.apply(this, arguments);
    };
})(Backbone.sync);

这样,如果将模型或集合作为localStorage属性,它将首先与 localStorage 同步,然后再进行原始同步。

示例模型和集合:

var BarModel = Backbone.Model.extend({
    urlRoot: 'some/url',
    localStorage: function() {
        return 'bars-' + this.id;
    },
});

var BarCollection = Backbone.Collection.extend({
    model: BarModel,
    url: '/some/url',
    localStorage: 'bars',
});
于 2016-11-26T22:09:32.410 回答