let's say I have :
var Book = Backbone.Model.extend();
var Collection = Backbone.Collection.extend({
model: Book,
url: '/books',
initialize: function(){
this.fetch();
})
})
How can I change the Collection
's url
when instantiating a new collection ?
var AdventureBooks = new Books({ url: '/books/adventure' })
does not work
var AdventureBooks = new Books({ category: 'adventure' })
and in the Collection definition:
url : '/books/' + this.category
does not work either.
Thanks.
The following should work:
I know that this a late reply, but I had a similar although slightly more complicated situation, and the selected answer didn't really help me.
I have a Conditions collection, and each Experiment model has multiple conditions, and I needed my url to be /api/experiments/:experimentId/conditions, but I didn't know how to access the experimentId from the empty Conditions collection.
In my Conditions collection url function, I did a console.log(this.toJSON()) and discovered that Backbone inserts a single dummy model in the empty collection with whatever attributes you passed in at it's creation time.
so:
I somehow doubt that this would be considered a best practice, hopefully someone else will respond with a better solution, but here's how I defined my Collection:
The best solution for me is the initialize method, look at this example:
use it as follows:
This work for me (tested with backbone 1.2.1):
use it as follows:
Like Daniel Patz pointed out , the problem lies in how you're instantiating the collection. I just struggled with this for a bit right now, so I thought I'd update this, even though the question is somewhat old.
The first argument is expected to be an array of models, with the options coming after. This should work:
If you want a dynamic URL, then Raynos' answer might be the way to go.
For some reason the parameters passed to Collection constructor (for example "url") are not set to the object. The collection uses only few of those (model and comparator).
If you want to pass the url via constructor you need to create initialize method that copies the necessary parameters to the object: