Backbone.js的:建模belongs_to的关系 [英] Backbone.js: Modeling a belongs_to relationship

查看:112
本文介绍了Backbone.js的:建模belongs_to的关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个帖子集合骨干的应用程序。所有职位都属于一个博客。创建一个新的职位要求我知道博客是属于: POST /博客/ 42 /岗位

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:

明知骨干不希望我对我的模型之间的关系模式,我只是把在网​​址属性到一个函数,包括博客ID:

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"

(请原谅CoffeeScript的。)现在我需要做的 blogId 已知的帖子集合。所以我只是套结它在路由器初始化函数:

(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?

推荐答案

这是解决这个问题的方法之一。另一种方法是创建一个博客的模型。说你给博客模型的帖子()方法。在这种情况下,可以使用类似的附接blogId的方法,但在博客模型。例如(也在的CoffeeScript,如上):

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):

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

,然后在PostsCollection你会:

and then in your PostsCollection you would have:

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

让您在路由器更改为:

allowing you to change your router to:

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()

修改您的结构,这样可能会导致额外的模式,但它使你的code更清洁的整体。

Modifying your structure like this might result in an extra model, but it makes your code much cleaner overall.

这篇关于Backbone.js的:建模belongs_to的关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆