Backbone.js:建模belongs_to关系
假设我有一个包含 Posts 集合的 Backbone 应用程序。所有帖子都属于博客。创建新帖子需要我知道它所属的博客:POST /blog/42/posts
这是我到目前为止想到的 - 请告诉我是否有更好的解决方案:
知道Backbone 并不希望我对模型之间的关系进行建模,我只是将 url
属性转换为包含博客 ID 的函数:(
class App.Collections.PostsCollection extends Backbone.Collection
model: App.Models.Post
url: -> "/blog/" + this.blogId + "/posts"
请原谅 CoffeeScript。)现在我需要制作帖子已知的 blogId
收藏。所以我只是将它添加到路由器初始化函数中:
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
这不可能是正确的?!
请赐教——您通常如何对这些嵌套集合进行建模?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是解决这个问题的一种方法。另一种方法是创建博客模型。假设您为 Blog 模型提供 posts() 方法。在这种情况下,您可以使用类似的方法附加 blogId,但在博客模型中。例如(也在 Coffeescript 中,如上所述):
然后在您的 PostsCollection 中您将:
允许您将路由器更改为:
像这样修改结构可能会产生额外的模型,但它使您的代码整体上更加清晰。
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.