我不會創建嵌套的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 /時間」