Reputation: 1554
I am having issues creating a multiple collections and models. I am trying to form a basic Backbone.js Collection.
I am having two issues.
Event
model is not actually being created (There is no id: 'No ID' in the attributes). I know that the collection Months forms Month models but I cannot explain why Events is not forming Event models.I have a collection of Months
of the model Month
. The model Month
has a collection of Events
of the model Event
as follows:
$(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();
});
An example of the JSON I am trying to interpret here:
{
"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"
}
]
}
]
}
Any help would be appreciated
Thank you
Upvotes: 0
Views: 225
Reputation: 18859
Remove the id from the defaults altogether.
The id is a representation of id's that are present in the back end; if the id on a Backbone model is present, then the library assumes that you are working with a model that exists in the back end (and has a corresponding id there).
If the model was not persisted to a data source yet, then the model doesn't have an id and should therefore be empty. Functionally, backbone will in that case perform a POST
instead of PUT
on save()
, when the model does not have an id defined.
{reset:true}
fires an explicit reset event on the entire collection (instead of the default set
per model), but this should not be required to fetch the models from the server.
For getting access to the models that were fetched, you should implement a callback function though, which takes the response of the model's fetch method as parameter. When you call this.fetch()
, a promise is returned, which you have yet to process.
Upvotes: 1