Skip to content Skip to sidebar Skip to footer

Localstorage And Url In One Backbone Collection

I have a collection, which fetches data from URL. BarCollection = Backbone.Collection.extend({ model: BarModel, url: // Some URL }); But the problem is that I want to fetch da

Solution 1:

To enable any collection or model to synchronize from both the localStorage and a server, Backbone's sync function can be overridden:

Backbone.sync = (function(sync) {
    returnfunction(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 localStorageif (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 wouldreturn sync.apply(this, arguments);
    };
})(Backbone.sync);

This way, if a model or a collection as a localStorage property, it'll first sync with the localStorage, then it'll make the original sync.

Example model and collection:

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

varBarCollection = Backbone.Collection.extend({
    model: BarModel,
    url: '/some/url',
    localStorage: 'bars',
});

Post a Comment for "Localstorage And Url In One Backbone Collection"