【问题标题】:Backbone.js: Modeling a belongs_to relationshipBackbone.js:为belongs_to 关系建模
【发布时间】:2011-11-22 14:34:11
【问题描述】:

假设我有一个带有 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

这不可能吧?!

请赐教——您通常如何为这些嵌套集合建模?

【问题讨论】:

  • 只是想知道,是否有特定原因在 blogCollection 中没有 blogModel 并以 postCollection 作为属性(属于 blogModel)来表示该 blogModel 的帖子?
  • 当然,我可能会这样做(只是到目前为止还不需要它)。不过,我该如何构造网址?我认为我无法访问拥有 postCollection 的 blogModel,可以吗? (除非我像上面的blogId 那样添加blog 属性,所以它回到了第一格。)
  • 您找到了满足您需求的简单解决方案。您可以对此感到高兴,也可以深入挖掘痛苦的黑暗世界。例如:github.com/PaulUithol/Backbone-relational

标签: model backbone.js


【解决方案1】:

这是解决此问题的一种方法。另一种方法是创建博客模型。假设你给 Blog 模型一个 posts() 方法。在这种情况下,您可以使用类似的方法来附加 blogId,但在博客模型中。例如(也在 Coffeescript 中,如上):

class App.Models.Blog extends Backbone.Model
  posts: () =>
    @_posts ?= new App.Collections.PostsCollection({blog: this})

然后在您的 PostsCollection 中您将拥有:

class App.Collections.PostsCollections extends Backbone.Collection
  url: () => "/blog/#{@options.blog.id}/posts"

允许您将路由器更改为:

class App.Routers.PostsRouter extends Backbone.Router
  initialize: (options) ->
    # Per your example, an ID of 42 is used below.
    # Ideally, you retrieve the Blog some other way.
    @blog = new App.Models.Blog({id: 42})
    @posts = @blog.posts()

像这样修改你的结构可能会产生一个额外的模型,但它会让你的代码整体上更简洁。

【讨论】:

    猜你喜欢
    • 2014-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-02
    相关资源
    最近更新 更多