2012-07-08 16 views
0

我正在使用主幹關係的主幹。我有兩個型號,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,我需要包括ClientAppointment文件文件,所以Snip.Models.Appointment類將在我引用它時存在。然而,Appointment引用Client,所以這是一種catch-22的情況。我不知道該怎麼辦。

+0

根據這個帖子(http://stackoverflow.com/questions/10060561/backbone-js-using-new-in-model-defaults-circular -reference),也許我不應該做'client:Snip.Models.Client()'。如果我不這樣做,但我在哪裏做? 'client'屬性需要是一個'Snip.Models.Client'。 – 2012-07-08 19:17:11

回答

0

首先,利用骨幹 - 關係時,不要忘了initialize反向關係:

Snip.Models.Client.setup() 

其次,在關鍵client您的默認值應該是新的客戶端模式的attrs(它將被Backbone-創建關係)。如果你沒有任何離開的空哈希:

client: {} 
+0

感謝您的回覆。你是說如果我調用'setup()',我可以期望Backbone-relational在'defaults'下面提取'client:{}'並自動生成一個新的'Client'對象? – 2012-07-09 16:51:22

+0

由於某種原因,它起初並不適用於我,但現在它確實如此。真棒。再次感謝。 – 2012-07-09 16:53:02