How to set a Collection's url
Solution 1
var Book = Backbone.Model.extend({
"url": function() {
return '/books/' + this.get("category");
}
});
Solution 2
The following should work:
var AdventureBooks = new Books();
AdventureBooks.url = '/books/adventure';
Solution 3
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:
var Book = Backbone.Model.extend({
initialize: function(props) {
this.url = props.url;
}
}
var book = new Book({url: "/books/all"});
Solution 4
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:
var AdventureBooks = new Books([], { url: '/books/adventure' })
If you want a dynamic URL, then Raynos' answer might be the way to go.
Solution 5
If you want to have dynamic urls for your collection, try this (tested with backbone 1.1.2):
Create an instance of your backbone collection and pass the dynamic url parameter as an option (the options object needs to be the the second argument as the first one is an optional array of models):
var tweetsCollection = new TweetsCollection(null, { userId: 'u123' });
Then inside of your collection, create a dynamic url function that uses the value from the options object:
var TweetsCollection = Backbone.Collection.extend({
url: function() {
return '/api/tweets/' + this.options.userId;
},
model: TweetModel
});
Running Turtle
Updated on July 04, 2020Comments
-
Running Turtle almost 4 years
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
'surl
when instantiating a new collection ?var AdventureBooks = new Books({ url: '/books/adventure' })
does not workvar AdventureBooks = new Books({ category: 'adventure' })
and in the Collection definition:
url : '/books/' + this.category
does not work either.Thanks.
-
Dan P. over 11 yearsThe initialize method is actually: initialize([models], [options]) according to the documentation
-
a--m almost 11 yearsThis was my case, I was trying to set url passing the object in the first parameter
new Books({ url: '/books/adventure' })
Thank you @Ruy Diaz -
Harry over 10 yearstake our the quotes on "url"
-
geon over 10 years@DanielPatz: You are thinking of the collection. The model is inited with initialize([attributes], [options]).
-
Stefan Hendriks over 10 yearsalso, this is a property fetched from a model. What about you use a url on a collection? That was the OP's question.