我在组织几个月后传入Backbone模型的JSON时遇到了一些麻烦(我得到了一个空集合)。我试图尽可能明确一些,因此Year Collection实际上是这样设置其每个参数的。
因此,我有一个称为Backbone的集合Year
,它是Backbone模型Month
的集合,而该模型又具有一个events属性,该事件是模型的集合Event
。
$(function(){
var Event = Backbone.Model.extend({
});
var Events = Backbone.Collection.extend ({
model: Event
});
var Month = Backbone.Model.extend ({
});
var Year = Backbone.Collection.extend ({
model: Month,
url: '/api/v1/calendar/2014'
});
window.Calendar = new Year();
var promise = Calendar.fetch();
promise.done(function(response){
if ('events' in response) {
console.log('Events found');
response = response.events;
// Cycle through events and add to Collection
for (var i = 0; i < response.length; i++) {
var currentMonth = response[i].startdate.split('-');
thisEvent = new Event(response[i]);
thisMonth = new Month({
'name': currentMonth[1],
'events': new Events(thisEvent)
});
Calendar.add(thisMonth);
console.log('Set ' + currentMonth[1] + ' with Event ' + response[i]);
}
} else {
console.error('Zero events');
}
}).fail(function(response){
console.error('Failed to fetch Calendar');
});
});
我传入的JSON非常简单,就像这样
{
"status": "success",
"year": 2014,
"events": [
{
"title": "None",
"startdate": "2014-01-23",
"description": "Event Description"
},
{
"title": "None",
"startdate": "2014-01-25",
"description": "Event Description 2"
}
]
}
我不太确定为什么我会得到一个空集合。我最不确定的事情是使用设置Month
模型new Events(response[i])
。理想情况下,我将events
使用a初始化密钥,new Events
然后将response[i]
其添加。
任何帮助将不胜感激,
谢谢
我通常这样做:
var promise = calendar.fetch();
promise.done(function(response){
//This is where you process the collection that is returned from the server.
}).fail(function(response){
//In case of failure
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句