gpt4 book ai didi

backbone.js - 如何在 Backbone.js v0.5 中构建深度嵌套的模型

转载 作者:行者123 更新时间:2023-12-04 14:51:02 28 4
gpt4 key购买 nike

假设每个A有0个或更多B,每个B有0个或更多C项。如何在 Backbone.js (v0.5) 中呈现这种关系。我想要像/A/a/B/b/C/c 这样的网址。下面的代码是在 coffeescript 中。我很困惑,如何在以下代码中设置 url 变量。

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

class A extends Backbone.Model
initialize: ->
@Bs = new Bs()
@Bs.parent=@
@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/
@Cs.parent=@

class Cs extends Backbone.Collection
model: C

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

最佳答案

我不会创建嵌套的 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"
}
}

子节点由自定义 Controller 组装,该 Controller 获取单个 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)

最后一行会触发一个事件“change:exercise/duration”

关于backbone.js - 如何在 Backbone.js v0.5 中构建深度嵌套的模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6581135/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com