Say I have a Backbone application with a Posts collection. All posts belong to a Blog. Creating a new post requires me to know the Blog it belongs to: POST /blog/42/posts
Here is what I came up with so far — please tell me if there is a better solution:
Knowing that Backbone doesn’t expect me to model the relationships between my models, I simply turned the url attribute into a function to include the Blog ID:
class App.Collections.PostsCollection extends Backbone.Collection
model: App.Models.Post
url: -> "/blog/" + this.blogId + "/posts"
(Please excuse the CoffeeScript.) Now I need to make the blogId known to the posts collection. So I’m just tacking it on in the router initialize function:
class App.Routers.PostsRouter extends Backbone.Router
initialize: (options) ->
this.posts = new App.Collections.PostsCollection()
this.posts.blogId = 42 # <----- in reality some meaningful expression ;-)
this.posts.reset options.positions
That just can’t be right?!
Please enlighten me — how do you usually model these nested collections?
This is one way to solve this problem. An alternative is to create a Blog model. Say you give the Blog model a posts() method. In this case you could use a similar method of attaching the blogId, but in the Blog Model. For example (also in Coffeescript, as above):
and then in your PostsCollection you would have:
allowing you to change your router to:
Modifying your structure like this might result in an extra model, but it makes your code much cleaner overall.