3

I have a Backbone Collection like so:

var ThreadCollection = Backbone.Collection.extend({
  url: '/api/rest/thread/getList'
});
var myCollection = new ThreadCollection();

And then I'm fetching it from the server using the data object to append the query parameters (so in this case it comes out '/api/rest/thread/getList?userId=487343')

myCollection.fetch({
  data: {
    userId: 487343
  }
})

There are other parameters that I may want to use instead of userId (groupId, orgId, etc) but I'd ideally define the data parameters upon initialization and from then on be able to run fetch() without specifying. Something like this:

var myCollection = new ThreadCollection({
  data: {
    userId: 487343
  }
});

myCollection.fetch()

but it doesn't work. Does anyone know if there's a way to do this? Thanks!

Evan Hobbs
  • 3,552
  • 5
  • 30
  • 42

1 Answers1

6

One way is to define a custom fetch method on your collection which calls the super fetch method with some overridable defaults:

var ThreadCollection = Backbone.Collection.extend({
    url: '/api/rest/thread/getList',
    fetch: function(options) {
        return Backbone.Collection.prototype.fetch.call(this, _.extend({
            data: {
                userId: 48743
            }
        }, options));
    }
});

var myCollection = new ThreadCollection();

myCollection.fetch();
Lukas
  • 9,765
  • 2
  • 37
  • 45