0

I'm using Backbone with Backbone-relational. I have two models, Appointment and Client, where a Client can have many Appointments. Here's my Client model definition (in 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'

And here's my Appointment model definition:

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'

Here's the problem: since Client references Appointment, I need to include the Appointment file before the Client file so the Snip.Models.Appointment class will exist by the time I reference it. However, Appointment also references Client, so it's kind of a catch-22 situation. I don't know what to do.

Jason Swett
  • 43,526
  • 67
  • 220
  • 351
  • According to this post (http://stackoverflow.com/questions/10060561/backbone-js-using-new-in-model-defaults-circular-reference), maybe I'm not supposed to do `client: Snip.Models.Client()`. If I don't do it there, though, where do I do it? The `client` attribute needs to be a `Snip.Models.Client`. – Jason Swett Jul 08 '12 at 19:17

1 Answers1

0

First, when using Backbone-Relational don't forget to initialize reverse relations:

Snip.Models.Client.setup()

Second, in your defaults in key client should be attrs for new client model (It will be created by Backbone-Relational). And if you don't have any leave empty hash:

client: {}
Igor Alekseev
  • 1,208
  • 12
  • 20
  • Thanks for the reply. Are you saying that if I call `setup()`, I can expect Backbone-relational to pick up that `client: {}` under `defaults` and automatically generate a new `Client` object? – Jason Swett Jul 09 '12 at 16:51
  • It didn't work for me at first for some reason, but now it does. Awesome. Thanks again. – Jason Swett Jul 09 '12 at 16:53