soultrust
soultrust

Reputation: 599

How do you override the sync method for a Backbone collection (as opposed to a model)?

I have a folder tree that fetches a collection based on the folder you click. If the user changes his mind and clicks another folder, I want to abort the previous fetch. As this is happens in multiple places within the project, I want to override the sync method on the collection. I've seen so many examples of model syncs, but not for collections. I also want to preserve the query string params. The official documentation states that collections also have a sync method, but I've never seen this done. Please point me in the right direction. Thanks in advance.

Upvotes: 4

Views: 2716

Answers (1)

poeticGeek
poeticGeek

Reputation: 1041

Backbone's Collection sync looks exactly the same as the Model's sync method:

// Proxy `Backbone.sync` by default.
        sync: function() {
            return Backbone.sync.apply(this, arguments);
        },

thats because both do the same, they simply "proxy" the Backbone.sync method. The reason they are there is to allow implementations to change the sync logic on a per type basis and not having to touch the main sync method which will influence all models and collections in your project.

I would advise doing something like the following for your collection because you probably dont want to mimic Backbone's sync logic yourself, it does quite a few things for you and messing with it can cause problems that could be hard to solve later on.

var MyCollectionType = Backbone.Collection.extend({

    sync: function(method, model, options){
          //put your pre-sync logic here and call return; if you want to abort

         Backbone.Collection.prototype.sync.apply(this, arguments); //continue using backbone's collection sync 
    }
});

Upvotes: 1

Related Questions