我正在使用具有Backbone关系的Backbone。我有两个模型,Appointment
和Client
,其中一个Client
可以有许多Appointments
。以下是我的Client
模型定义(在CoffeeScript中):
class Snip.Models.Client extends Backbone.RelationalModel
paramRoot: 'client'
relations: [
type: Backbone.HasMany
key: 'appointments'
relatedModel: 'Snip.Models.Appointment'
collectionType: 'Snip.Collections.AppointmentsCollection'
reverseRelation:
type: Backbone.HasOne
key: 'client'
includeInJSON: 'id'
]
defaults:
name: null
phone: null
email: null
notes: null
active: null
class Snip.Collections.ClientsCollection extends Backbone.Collection
model: Snip.Models.Client
url: '/clients'
这是我的Appointment
模型定义:
class Snip.Models.Appointment extends Backbone.RelationalModel
paramRoot: 'appointment'
defaults:
time_block_type_code: 'APPOINTMENT'
start_time: null
stylist: null
salon: null
client: Snip.Models.Client() # This doens't work
class Snip.Collections.AppointmentsCollection extends Backbone.Collection
model: Snip.Models.Appointment
url: '/appointments'
问题是:由于Client
引用了Appointment
,所以我需要在Client
文件之前包含Appointment
文件,这样当我引用Snip.Models.Appointment
类时,它就会存在。然而,Appointment
也引用Client
,所以这是一种进退两难的情况。我不知道该怎么办。
首先,当使用Backbone Relational时,不要忘记初始化反向关系:
Snip.Models.Client.setup()
其次,关键字client
中的默认值应该是新客户端模型的attrs(它将由Backbone Relational创建)。如果你没有任何空散列:
client: {}