Javascript – backbone.js collection get vars

backbone.jscollectionsjavascript

This seems like an obvious one, but I'm somehow missing it…

How do you send options along with a backbone.js collection fetch()?

Or, from a broader point of view: I have a large dataset on the server, messages in this case, that I want to make accessible through a collection. Seeing as there could be thousands of messages I don't want to simply fetch and store all of them at once, so my collection would have to at least understand limits and offsets. Not to mention querying filtered or sorted lists.

Is a backbone collection even the way to handle this?

Cheers

Best Answer

I've been messing with Backbone for a couple days now and I had to deal with this problem almost immediately and I looked at this solution, but I found it clunky. After reading some more backbone documentation I discovered you can actually override any of the jQuery.ajax options within the fetch() method. So for example

Posts = Backbone.Collections.extend({
  model: Post,
  url: '/posts'
});

Now when you want to call fetch just send it whatever parameters you wish. e.g.

var posts = new Posts();
posts.fetch({ data: { page: 3, pagesize: 10, sort: 'asc' } });

This will produce the following request:

http://yourdomain/posts?page=3&pagesize=10&sort=asc

Anyway, I know you've already accepted an answer, but hopefully this will help someone.