由于使用Backbone-relational的循环引用,无法设置默认属性

时间:2012-07-08 19:13:15

标签: backbone.js backbone-relational

我正在使用Backbone与Backbone关系。我有两个模型,AppointmentClient,其中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,我需要在Appointment文件之前包含Client文件,以便Snip.Models.Appointment类存在于我引用它的时间。但是,Appointment 引用了Client,所以这是一种捕获22的情况。我不知道该怎么做。

1 个答案:

答案 0 :(得分:0)

首先,当使用Backbone-Relational时,不要忘记initialize反向关系:

Snip.Models.Client.setup()

其次,在密钥client中的默认值应该是新客户端模型的默认值(它将由Backbone-Relational创建)。如果你没有留空哈希:

client: {}