I would like to know what is the difference between using url
or urlRoot
. I have read the documentation (backbonejs.org/#Model-url), but I still feel that I lack knowledge in this area and I would like to know more. When do you have to use url
? And in another instance when do you have to use urlRoot
?
问题:
回答1:
.urlRoot
is only available in a Model, and is only useful when either a model is not part of a collection, or when you want to override the .url
property of the collection which that model is part of.
In other words, a model doesn't require neither .url
nor .urlRoot
property when it is part of a collection with a .url
property set, in which case this model will use that collection's .url
as it's own .urlRoot
.
Here are several examples that show the difference. When you run the scripts, the http requests can be seen in browser's network panel.
Example 1. Post is not part of a collection. urlRoot
defines the base part of the url. When a model is fetched, it's id is appended to the urlRoot
.
var Post = Backbone.Model.extend({
urlRoot: 'http://jsonplaceholder.typicode.com/posts'
});
var secondPost = new Post({ id: 2 });
secondPost.fetch();
/*requests http://jsonplaceholder.typicode.com/posts/2 */
<script src='http://code.jquery.com/jquery.js'></script>
<script src='http://underscorejs.org/underscore.js'></script>
<script src='http://backbonejs.org/backbone.js'></script>
Example 2. Calling fetch on a model which is a part of a collection uses the collection's url
as the urlRoot
var Post = Backbone.Model.extend();
var Posts = Backbone.Collection.extend({
url: 'http://jsonplaceholder.typicode.com/posts',
model: Post
});
var posts = new Posts();
posts.add({id: 2});
posts.first().fetch();
/*requests http://jsonplaceholder.typicode.com/posts/2 */
<script src='http://code.jquery.com/jquery.js'></script>
<script src='http://underscorejs.org/underscore.js'></script>
<script src='http://backbonejs.org/backbone.js'></script>
Example 3. url
set on a model will literally use that url for any model instance.
var Post = Backbone.Model.extend({
url: 'http://jsonplaceholder.typicode.com/posts'
});
var secondPost = new Post({ id: 2 });
secondPost.fetch();
/*requests http://jsonplaceholder.typicode.com/posts */
<script src='http://code.jquery.com/jquery.js'></script>
<script src='http://underscorejs.org/underscore.js'></script>
<script src='http://backbonejs.org/backbone.js'></script>
Example 4. url
can be a function and it starts to make sense again.
var Post = Backbone.Model.extend({
url: function(){
return 'http://jsonplaceholder.typicode.com/posts/' + this.get('slug');
}
});
var secondPost = new Post({ slug: 2 });
secondPost.fetch();
/*requests http://jsonplaceholder.typicode.com/posts/2 */
<script src='http://code.jquery.com/jquery.js'></script>
<script src='http://underscorejs.org/underscore.js'></script>
<script src='http://backbonejs.org/backbone.js'></script>