2011-07-05 94 views
6

假設每個A有0個或多個B,每個B有0個或多個C個項目。如何在Backbone.js(v0.5)中介紹這種關係。我希望有像/ A/A/B/B/C/C這樣的網址。以下代碼在coffeescript中。我很困惑,如何在後面的代碼中設置url變量。如何在Backbone.js v0.5中構建深度嵌套模型

class As extends Backbone.Collection 
    url: "/A" 
    model: A 

class A extends Backbone.Model 
    initialize: -> 
    @Bs = new Bs() 
    @[email protected] 
    @Bs.url="/A/#{@id}" 

class Bs extends Backbone.Collection  
    model: B 

class B extends Backbone.Model 
    initialize: -> 
    @Cs = new Cs() 
    @Cs.url = ??? # => /A/a/B/b/C/ 
    @[email protected] 

class Cs extends Backbone.Collection 
    model: C 

class C extends Backbone.Model 
    url: #?? url => /A/a/B/b/C/c 

回答

7

我不會創建嵌套的URL,除非你真的有一個好的例子。每個資源可以由資源名稱和ID來定義。對象之間的關係是內部的。

http://foo.com/a/:id.json 
http://foo.com/b/:id.json 
http://foo.com/c/:id.json 

這就是說,大量的命中服務器拉出嵌套的對象並不是很理想。你最好有一個返回嵌套JSON

http://foo.com/a/:id.json 

例如,一個單一的資源我回來從我的服務器數據的模樣

{ 
    "id": 372, 
    "context": "office_work", 
    "date_of_entry": "2011-7-05 15:22:00", 
    "blood_glucose_measurement": 98, 
    "food": { 
    "exchanges": "98", 
    "list": "burger fries" 
    }, 
    "exercise": { 
    "duration": "28", 
    "list": "running shopping" 
    } 
} 

子節點通過自定義控制器,是以個人組裝db記錄並製作數據樹。

但是,您現在遇到了麻煩,因爲backbone.js本身只支持平面結構。我對基本Backbone.Model進行了一些修改,以支持處理樹狀結構。

如果它可能對您有用,我會將它粘貼到此處。

#= require jquery 
#= require underscore 
#= require backbone 
# 
class RailsModel extends Backbone.Model 

    initialize: (attributes) -> 
    data = {} 

    for k,v of @attributes 
     if v.constructor.name == "Object" 
     data[k] = new RailsModel(v) 

    @set data, {silent: true} 

    get: (field)-> 
    val = @ 
    first = true 
    for p in field.split('/') 
     if first 
     val = super(p) 
     else 
     # This allows returning *undefined* rather 
     # than an exception if the parent of a deeply 
     # nested node does not exist. 
     val = if val? then val.get(p) else undefined 
     first = false 
    val 

    # Allow heirarchical setting of objects 
    # 
    # Example 
    # 
    # model.set_field('root/child', 10) 
    # 
    # Will create the path if it does not exist 
    set_field: (field, value, silent=false)-> 
    path = field.split('/') 

    node = undefined 
    val = @ 
    for p in field.split('/') 
     node = val 
     val = node.get(p) 
     if not val? 
     data = {} 
     val = new RailsModel 
     data[p] = val 
     node.set data 

    data = {} 
    data[p] = value 
    node.set data 

    if not silent and /\//.test(field) 
     @trigger("change:#{field}", @model, value) 
     @trigger("change", @model) 

window.RailsModel = RailsModel 

您可以使用它像

model = new RailsModel 
model.url = "/data" 
model.fetch() 
model.get('excercise/duration') 
model.set_field('excercise/duration', 25) 

最後一行將觸發事件 「的變化:鍛鍊; Tibial /時間」