Backbone.js更新集合中Collection的模型

时间:2014-12-28 03:58:21

标签: json backbone.js collections

我在组织JSON时遇到了一些麻烦,我传入Backbone模型几个月(我收到一个空集合)。我试图尽可能明确,所以Year Collection实际上是设置它的每个参数。

所以我有一个名为Year的Backbone集合,它是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初始化new Events密钥,然后将response[i]添加到其中。

非常感谢任何帮助,

谢谢

2 个答案:

答案 0 :(得分:1)

我通常这样做:

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 
}); 

答案 1 :(得分:0)

我认为你需要做的就是覆盖Collections parse函数并执行以下操作:

  parse: function(response) {
    this.status = response.status;
    this.year = response.year;
    return response.events;
  }

parse函数应该始终返回一个从中填充集合的数组。 希望这会有所帮助。