2011-11-22 49 views
2

假設我有一個包含Posts集合的Backbone應用程序。所有帖子都屬於博客。創建一個新的職位要求我知道博客它屬於:POST /blog/42/postsBackbone.js:對belongs_to關係建模

這裏是我想出了迄今爲止 - 請告訴我,如果有一個更好的解決方案:

明知骨幹不希望我對我的模型之間的關係進行建模,我只是翻了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 

那只是不對的?!

請賜教 - 你通常如何建模這些嵌套集合?

+1

只是想知道,是否有一個具體的原因,你沒有blogCollection中的blogModel與postCollection作爲屬性(的博客模型)代表博客模型的職位? – Sander

+0

當然,我可能會這樣做(到目前爲止,並不需要它)。不過,我該如何構建網址?我不認爲我可以獲得擁有postCollection的blogModel,對嗎? (除非我像上面使用'blogId'這樣的'blog'屬性,所以它回到了原來的一個。) –

+1

您已經找到了一個簡單的解決方案來滿足您的需求。你可以對它感到滿意,或者你可以深入挖掘一個黑暗的世界。 例如:https://github.com/PaulUithol/Backbone-relational – maxl0rd

回答

0

這是解決此問題的一種方法。另一種方法是創建一個博客模型。假設你給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() 

修改像這樣的結構可能會導致一個額外的模型,但它使您的代碼整體更清潔。