this.id is undefined in Blog.Collections.Posts class. What’s wrong?
Blog collection
Blog.Collections.Posts = Backbone.Collection.extend({
model: Blog.Models.Post,
url: function() {
console.log(this.id);
if (this.id) {
return '/api/posts/'+this.id
}
else{
return '/api/posts'
}
}
});
My router:
Blog.Routers.Posts = Backbone.Router.extend({
routes: {
"" : "index",
"entry/:id" : "show"
},
show: function(id) {
var collection = new Blog.Collections.Posts({id: id});
collection.fetch({
success: function() {
var view = new Blog.Views.PostsIndex({ collection: collection });
console.log(collection);
}
});
}
});
Collections don’t have an id by default. Unless you’re explicitly assigning an id to your collection,
this.idbecomes undefined. IDs are standard attribute of models. What you want to do is simply:Backbone models, if they are a part of a collection will use the collection
urlwhen fetching and saving. Thus, if you do something like this:It will automatically goto:
Hope this helps.