2014-12-27 104 views
0

我在創建多個集合和模型時遇到了問題。我正在嘗試構建一個基本的Backbone.js集合。在Backbone.js中形成多個集合和模型的問題

我有兩個問題。

  1. 望着通過什麼傳遞給視圖我可以看到實際上沒有被創建的Event模型(沒有ID:在屬性「無ID」)的控制檯日誌。我知道收集月份形成月份模型,但我無法解釋爲什麼事件不會形成事件模型。
  2. 集合僅在Months集合初始化爲reset:true時形成。我不知道如何解釋這

我有一個Months的模型Month的集合。

{ 
"status": "success", 
"year": 2014, 
"months": [ 
    { 
     "month": 1, 
     "events": [ 
      { 
       "title": "None", 
       "startdate": "2014-01-23", 
       "enddate": "None", 
       "description": "description 1" 
      } 
     ] 
    }, 
    { 
     "month": 12, 
     "events": [ 
      { 
       "title": "None", 
       "startdate": "2014-12-24", 
       "enddate": "None", 
       "description": "description 2" 
      }, 
      { 
       "title": "None", 
       "startdate": "2014-12-25", 
       "enddate": "None", 
       "description": "description 3" 
      } 
     ] 
    } 
] 
} 

任何幫助,將不勝感激

$(function(){ 
var Event = Backbone.Model.extend({ 
    defaults: { 
     id: 'No ID', 
     description: 'No description', 
     startdate: 'No startdate' 
    } 

}); 

var Events = Backbone.Collection.extend({ 
    model: Event, 

    parse: function(response) { 
     return response; 
    } 
}); 

var Month = Backbone.Model.extend({ 
    defaults: function() { 
     return { 
      events: new Events(this.get('events')) 
     }; 
    } 
}); 

var Months = Backbone.Collection.extend({ 
    model: Month, 
    url : '/api/v1/calendar/2014', 

    initialize: function(){ 
     this.fetch({ 
      reset: true 
     }); 
    }, 

    parse: function(response) { 
     if ('months' in response) { 
      console.log('Months Collection: ' + response); 
      return response.months; 
     } else { 
      console.error('No months found.'); 
     } 
    } 

}); 

window.Calendar = new Months(); 
}); 

的JSON我想在這裏解釋的例子:Month有模型的Events集合Event如下模型謝謝

回答

1

完全從默認值中刪除id。
該id是在後端存在的id的表示;如果Backbone模型中的id存在,那麼庫假定您正在使用存在於後端的模型(並且在那裏具有對應的id)。
如果模型尚未持久保存到數據源,那麼該模型沒有id,因此應爲空。在功能上,骨幹將在這種情況下執行POST而不是PUTsave(),當模型沒有定義的id。

{reset:true}在整個集合(而不是每個模型的默認set)上觸發顯式重置事件,但這不應該需要從服務器獲取模型。 爲了獲得對已獲取模型的訪問權限,您應該實現一個回調函數,該函數將模型的獲取方法的響應作爲參數。當您致電this.fetch()時,將返回一個您尚未處理的承諾。