Search code examples
jsonbackbone.jscollections

Backbone.js updating a Collection's model in the collection


I am having a bit of trouble organising the JSON I pass in into Backbone models as months (I am getting an empty collection). I am trying to be explicit as possible so the Year Collection is actually setting each of its parameters like so.

So I have a Backbone collection called Year which is a collection of Backbone models Month which in turn has an events attribute which is a collection of the model 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');
}); 
});

The JSON I pass in is very simple, something like this

{
"status": "success",
"year": 2014,
"events": [
    {
        "title": "None",
        "startdate": "2014-01-23",
        "description": "Event Description"
    },
    {
        "title": "None",
        "startdate": "2014-01-25",
        "description": "Event Description 2"
    }
]
}

I am not quite sure why I get an empty collection. The thing I am least certain about is setting the Month model with new Events(response[i]). Ideally I would initialize the events key with a new Events and then add response[i] to it.

Any help would be greatly appreciated,

Thank you


Solution

  • I do it this way usually:

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