Ivan Morgillo
Ivan Morgillo

Reputation: 3844

Fetch Backbone Collection by Model IDs list

I have a REST API serving a few URLs:

/rest/messages

provides all messages. A message is a JSON/Backbone Model

{ 
  title: 'foo',
  body : 'bar'
}

To get a single message I have:

/rest/messages/:id

Is it possible to fetch a Backbone Collection using message IDs array? I don't want the whole message list, but just a few messages I specify by ID.

I could fetch Models one-by-one and fill up the Collection, but I'm wondering if Backbone has a cleaner way to do this. Thanks

Upvotes: 0

Views: 1698

Answers (2)

Naor
Naor

Reputation: 24053

The url property of collection reference to the collection location on the server. When you use fetch, backbone uses that url.
The url property can be also a function that returns the url. So you can do something like that:

var ids = [1,2,3]
var messages = new MessegecCollection();
messages.url = function() {
    return "/rest/messages/"+ids.join("-"); //results "/rest/messages/1-2-3"
}
messages.fetch();

You can also create a method in your collection that generated and set the url, or even fetchs a set of models.
Now all you have to do is to support this url: /rest/messages/1-2-3

Hope this helps!

Upvotes: 1

Cyclone
Cyclone

Reputation: 1580

According to documentation, you can pass ajax options to the fetch call. So, you can pass ids as data attribute to the fetch call being done and based on it, return the respective models from the server.

For example (when doing fetch),

collection.fetch({
  data : {
    message_ids : [1, 3, 5] // array of the message ids you want to retrieve as models
  }
})

This message_id array will be accessible as parameters (not sure of the name in your case) in the server code being executed at /rest/messages, from there you can return only specific models based on ids you receive as message_ids. The only thing you need is, client side must be aware of the ids of all the message models it needs.

You can use any data structure instead of array to send message_ids.

Upvotes: 6

Related Questions