I'm starting to use backbone.js and I'm confused as to why you can specify url's in a bunch of different ways. It doesn't seem like the collection url is used anywhere except in the model url function. So is there any harm in just setting urlroot on all of my models and never using collection urls?
2 Answers
there is no harm at all, you can work perfectly fine at the model level doing updates, deletes etc, but when you want to GET a set of models from the server all at once it comes handy to do something like this.
Books = Backbone.Collection.extend({
url : "/books"
});
books = new Books();
books.fetch(); // this will line will make a GET request to your backend, the result will
// be a list of models.

- 3,727
- 20
- 24
-
If this collection wasn't supposed to contain all of the instances of a model though, how would fetch know which models to fetch? Like if I had a a student model, a student collection, and a class model that had a student collection in it, would I just have to manually set the url for each student collection to be somehow relative to the class model's id? – bdwain May 28 '13 at 04:58
-
as every property in Javascript it can be a value or a function, for this specific example you could use a function to "calculete" the route of the student collections of the class. something like url : function (){ retunr "students" + class.id;} this way when you instanciate your class you can call this.class.students.fetch(); – Rayweb_on May 28 '13 at 05:20
In Backbone.js, Models and Collections are related to 'structuring' data, and Backbone provide methods for doing this. With Restful routes, you most often need updates/fetches like this:
GET /students
[{name: "...", ...}]
GET /students/1
{name: "..."}
As you observed, the URLs are similar, but in most cases processing the response of a Collection and Model fetch, will look different. Since conceptually, Models are part of a Collection, Model URLs can in most cases be resolved from the collection. There are other APIs where models and collection don't match, and you need to set the URLs yourself (e.g. a session model, that does not belong to a collection)
Maybe it also helps to compare the documentation for the Model and Collection fetch:
This might also help to understand the Backbone way of thinking: http://jonathanotto.com/blog/backbone_js_for_the_everyman.html

- 6,986
- 10
- 48
- 78