4

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.

soultrust
  • 581
  • 1
  • 7
  • 17
  • 3
    Overriding a collection's `sync` is the same as doing it for a model, they all look like `return (this.sync || Backbone.sync).call(this, ...);` in the source. The only interesting part is that a collection's `sync` will only be called with `'read'` as the `method` parameter. – mu is too short Oct 15 '12 at 23:19
  • @mu but it would be interesting to override collection.sync for batch saves etc – Alexander Mills Aug 23 '15 at 21:23

1 Answers1

1

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 
    }
});
poeticGeek
  • 1,001
  • 10
  • 14