Backbone collection doesn't fetch by ajax if has set localStorage object

367 views Asked by At

I want to use backbone.localStorage.js plugin in my app and here is a code sample:

Module.Vehicles = Backbone.Collection.extend({
        initialize : function(options) {
            this.customerId = options.customerId;
        },
        url : function() {
            var url = App.Config.RESTPath + '/vehicle';
            if(this.customerId) {
                url = url + '?customerId='+this.customerId;
            }
            return url;
        },
        localStorage: new Backbone.LocalStorage("vehicles"),
        model : Module.Vehicle,
        parse : function(response) {
            this.allVehiclesNumber = response.allVehiclesNumber;
            this.customers = response.customers;
            return response.vehicles;
        }
    });

    Module.getVehicles = function(customerId) {
        var result = new Module.Vehicles({
            'customerId' : customerId
        });
        result.fetch();
        return result;
    };

Everything works great (collection has proper records) if I add a comment in the line:

localStorage: new Backbone.LocalStorage("vehicles"),

But if it is not commentend there are no recordsfetch.

What I missed?

BR, Tomasz.

1

There are 1 answers

0
nikoshr On

If you check Backbone.localStorage source code, you will see that it overrides the way Backbone syncs its data : if you have a localStorage declared in you model/collection, the normal sync is discarded and replaced by a local storage.

You can alter this behavior by providing your own custom Backbone.sync. For example, this will use both versions:

Backbone.sync = function(method, model, options) {
  if(model.localStorage || (model.collection && model.collection.localStorage)) {
    Backbone.localSync.call(this, method, model, options);
  }

  return Backbone.ajaxSync.call(this, method, model, options);
};

And a Fiddle to play with http://jsfiddle.net/nikoshr/F7Hkw/